Web App Development

Minimal Backbone.localStorage example

I struggled to get Backbone.localStorage working, mostly due to this "Object has no method 'parse'" error. Below is a minimal example without views, you can download the full code from Github.

The Model and the Collection

In order to use Backbone.localStorage to save a model we also need a collection. The `localStorage` property of the collection needs to be set to a new Backbone.LocalStorage object with an identifier for the collection that is used when reading or writing the model values to LocalStorage.
var Note = Backbone.Model.extend({
defaults: function(){
return {
content: "Note created on " + new Date().toISOString()
}
}
});

var NoteCollection = Backbone.Collection.extend({
model: Note,
localStorage: new Backbone.LocalStorage("choose-some-identifier")
});
The defaults function of the model returns an object with a content property that makes it easy to identify when the model was added to the collection and if it's new or has been fetched from local storage.

Adding and saving Note models

Backbone collections have a fetch method that retrieves models from the server or, in this case, local storage.
Before calling save on the model we need to add it to the collection, otherwise Backbone would attempt to use an Http request to store it on a server.
var myNotes = new NoteCollection();
myNotes.fetch();
var note1 = new Note();
myNotes.add(note1);
note1.save();

myNotes.models.forEach(function(model){
console.log("Model in collection: " + model.get("content"));
});
After loading the page a few times the console output might look like this:
Model in collection: Note created on 2013-01-22T12:25:33.735Z
Model in collection: Note created on 2013-01-22T12:25:34.897Z
Model in collection: Note created on 2013-01-22T12:25:40.786Z
Model in collection: Note created on 2013-01-22T12:27:42.161Z
In local storage the models are stored like this:


Comments


Follow me on Twitter