Saving a model in local storage

前端 未结 2 1092
渐次进展
渐次进展 2020-12-13 20:46

I\'m using Jerome\'s localStorage adapter with Backbone and it works great for collections.

But, now I have a single model that I need to save. So in my model I set

相关标签:
2条回答
  • 2020-12-13 21:14

    I'm new to backbone.js too, but it looks like the persistence model is analogous to database tables. That is to say, it's designed to create/delete/read records from a table. The localStorage adapter does the same, so what you are doing there is creating a Msg "table" in localStorage, and creating a new Msg "record" each time, and the adapter gives each new Msg a unique id.

    If you just have one object, it's probably easier to just use localStorage directly. The API is really straight forward:

    localStorage.setItem("key","value");
    

    Keep in mind that localStorage only deals with key/value pairs as strings, so you'd need to convert to/from string format.

    Take a look a this question for more on doing that:

    Storing Objects in HTML5 localStorage

    0 讨论(0)
  • 2020-12-13 21:31

    I ran into same issue. Maybe you have something similar to this

    var Settings = Backbone.Model.extend({
      localStorage: new Store("Settings"),
      defaults: { a: 1 }
    });
    
    var s = new Settings;
    s.fetch();
    

    I changed to

    var s = new Settings({ id: 1 });
    

    localStorage adapter check for id like

     case "read":    resp = model.id ? store.find(model) : store.findAll(); break;
    

    so 0 or "" for id wont work and it will return all models in one

    0 讨论(0)
提交回复
热议问题