Here’s the official sample app:
http://documentcloud.github.com/backbone/docs/todos.html
I am confused about the relationship between the collection and its property localStorage = new Store(..)
Shouldn’t this be in the model because you can’t do a collection.save() anyway?
In addition, I tried implementing something like it, and it doesn’t work
var Person = Backbone.Model.extend({
defaults: {
name:'no-name',
age:0
}
});
var Persons = Backbone.Collection.extend({
model: Person,
localStorage: new Store('Persons'),
initialize: function(){
console.log('collection initialized');
}
});
window.people = new Persons();
var p1 = new Person({name:'JC',age:24});
p1.save({text:'hello'}); //<--- Uncaught TypeError: Cannot read property 'localStorage' of undefined
Can anyone help me figure this out?
It’s actually the
.create()function of a collection that allows the collection to “save” to localStorage.source-code of todo sample:
This then allows the model instance to manipulate it using the
.save({attr:value})function.Calling
modelInstance.save()without a definedlocalStorageproperty in the model’s constructor function will cause the error:Uncaught TypeError: Cannot read property 'localStorage' of undefinedHowever, being that the model is now saved in the localStorage through the
collectionInstance.create()method,modelInstance.save({attr:value})can now be used to modify it.So, in conclusion, Models only has the
save()function which allows persistence, but the Collection object has thecreate()function that allows persistence.In order to use these, REST urls within the collection and model must be properly set up or the localStorage plugin must be instantiated within the Constructor Function of either (depending on setup)