Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

javascript - Saving a model in local storage

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:

localStorage: new Store("msg")

I then do my saves and fetch. My problem is that everytime I do a refresh and initialize my app a new representation of my model is added to localStorage, see below.

What am I doing wrong?

window.localStorage.msg = {
  // Created after first run
  "1de5770c-1431-3b15-539b-695cedf3a415":{
    "title":"First run",
    "id":"1de5770c-1431-3b15-539b-695cedf3a415"
  },
  // Created after second run
  "26c1fdb7-5803-a61f-ca12-2701dba9a09e":{
    "0":{
      "title":"First run",
      "id":"1de5770c-1431-3b15-539b-695cedf3a415"
    },
      "title":"Second run",
      "id":"26c1fdb7-5803-a61f-ca12-2701dba9a09e"
    }
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...