如何从Backbone.LocalStorage获取Backbone.Collection

时间:2012-09-26 17:03:22

标签: javascript backbone.js local-storage

假设我可以从javascript控制台获得以下结果:

var ls = new Backbone.LocalStorage("items"); 
ls; // {"name":"items","records":["1244f588-be3d-c493-5c86-b2abb997af82"]}

我该如何从Backbone.Collection获取Backbone.LocalStorage

P.S .:
该集合看起来像

[
{
"title":"test",
"completed":false,
"order":1,
"id":"1244f588-be3d-c493-5c86-b2abb997af82"
},
{
"title":"test2",
"completed":false,
"order":2,
"id":"8a8658b9-b636-eac3-4c54-03c279a73c2d"
}
]

1 个答案:

答案 0 :(得分:10)

创建一个空集合,collection.localStorage设置为Backbone.LocalStorage对象并获取它:

var c = new Backbone.Collection();
c.localStorage = new Backbone.LocalStorage("items");
c.fetch();
console.log(c.pluck('id'));

或使用findAll对象上的Backbone.LocalStorage来获取存储中的一系列模型:

var ls = new Backbone.LocalStorage("items");
console.log(ls.findAll());

http://jsfiddle.net/nikoshr/8pHNG/

一起玩的小提琴