Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
}
]
like image 888
Lorraine Bernard Avatar asked Sep 26 '12 17:09

Lorraine Bernard


People also ask

How can I get specific data from localStorage?

To get items from localStorage, use the getItem() method. getItem() allows you to access the data stored in the browser's localStorage object.

What is localStorage in JSON?

localStorage An implementation of Client-side Storage. JSON (JavaScript Object Notation) a syntax for serializing objects, arrays, numbers, strings, booleans, and null.

What is backbone web app?

js is a JavaScript rich-client web app framework based on the model–view–controller design paradigm, intended to connect to an API over a RESTful JSON interface. Backbone is known for being lightweight, as its only hard dependency is on one JavaScript library, Underscore.


1 Answers

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/

like image 155
nikoshr Avatar answered Nov 15 '22 19:11

nikoshr