Duplication localStorage data using backbone.js + backbone.localStorage.js

爱⌒轻易说出口 提交于 2019-12-21 22:21:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!