Lorraine Bernard
Lorraine Bernard

Reputation: 13400

How to get Backbone.Collection from Backbone.LocalStorage

Let's suppose I can get from the javascript console the following result:

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

how should I get the Backbone.Collection from the Backbone.LocalStorage?

P.S.:
the collection looks like

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

Upvotes: 9

Views: 6162

Answers (1)

nikoshr
nikoshr

Reputation: 33344

Either create an empty collection with collection.localStorage set to your Backbone.LocalStorage object and fetch it:

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

or use findAll on your Backbone.LocalStorage object to get an array of models in storage:

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

A Fiddle to play with http://jsfiddle.net/nikoshr/8pHNG/

Upvotes: 10

Related Questions