2

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.

RaTiO
  • 979
  • 2
  • 17
  • 33
  • 1
    Looks like the problem is that `Backbone.localStorage` [is meant to work with Collections and it doesn't work properly with Models](http://stackoverflow.com/questions/7544503/backbone-js-saving-one-model-in-local-storage). – fguillen May 11 '12 at 10:18
  • Mmmm... It's strange because in the tests folder of backbone.localstorage github they show an example to use it with a Model (book)... https://github.com/jeromegn/Backbone.localStorage/blob/master/tests/test.js – RaTiO May 11 '12 at 10:35
  • I'm playing with [this jsFiddle](http://jsfiddle.net/fguillen/CPuYH) and I see a very weird behavior in the last `console.log` instead of seeing a hash of attributes I see an array of attributes of all Models saved in the past. Try to execute the code several times. Also [beware with loggin Objects in the JS console](http://stackoverflow.com/questions/9911637/backbone-js-model-get-returning-undefined-even-though-i-can-see-the-attribut/9912865#9912865) – fguillen May 11 '12 at 12:15

1 Answers1

2

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...

RaTiO
  • 979
  • 2
  • 17
  • 33