问题
I'm using backbone + backbone.localStorage to persist my data, and I get a wrong behavior:
I've got a model settings with one attribute called user
Settings = Backbone.Model.extend({
localStorage : new Backbone.LocalStorage('settingsStore')
});
var settings = new Settings();
settings.set({user: 'USERNAME'});
settings.save();
After this code if I output the settings.attributes data in weinre I get the following:
settings.attributes
Object
id: "3ac78cfb-ad60-1ab8-8391-f058ae9bfcfb"
user: "USERNAME"
__proto__: Object
Then I save the model to the localStorage, clear, and fetch it again:
settings.save();
settings.clear();
settings.fetch();
And the problem is that if I output the settings.attributes, now this attributes are stored inside a nested object:
settings.attributes
Object
0: Object
id: "3ac78cfb-ad60-1ab8-8391-f058ae9bfcfb"
user: "USERNAME"
__proto__: Object
__proto__: Object
And the problem is when I set the user name again in order to modify, a new attribute is added like this:
settings.attributes
Object
0: Object
id: "3ac78cfb-ad60-1ab8-8391-f058ae9bfcfb"
user: "USERNAME"
__proto__: Object
user: "NEWUSER"
__proto__: Object
And if I save this model, and fetch it again I get 2 new objects on the attributes... and it keeps growing each time.
回答1:
The answer to the question given by fguillen link gives the correct answer to this problem.
You just need to create the model object with a hardcoded "ID" if you want to save it correctly.
After doing this:
var settings = new Settings({ id: 1 });
The save() and fecth() methods are working correctly. Obviously you have to take care not repeating 2 ID's...
来源:https://stackoverflow.com/questions/10549056/duplication-localstorage-data-using-backbone-js-backbone-localstorage-js