[英]Saving a model in local storage
I'm using Jerome's localStorage adapter with Backbone and it works great for collections. 我正在使用Jerome的localStorage适配器和Backbone,它非常适合收藏。
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.
我的问题是,每当我刷新并初始化我的应用程序时,我的模型的新表示将添加到localStorage,请参阅下文。
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"
}
}
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 localStorage适配器检查id如何
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
或""
对于id不会工作,它将返回所有模型中的一个
I'm new to backbone.js too, but it looks like the persistence model is analogous to database tables. 我也是backbone.js的新手,但看起来持久性模型类似于数据库表。 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.
localStorage适配器也是如此,所以你在那里做的是在localStorage中创建一个Msg“表”,并且每次都创建一个新的Msg“记录”,并且适配器为每个新的Msg提供一个唯一的id。
If you just have one object, it's probably easier to just use localStorage directly. 如果你只有一个对象,那么直接使用localStorage可能更容易。 The API is really straight forward:
API非常简单:
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. 请记住,localStorage仅将键/值对作为字符串处理,因此您需要转换为字符串格式。
Take a look a this question for more on doing that: 看看这个问题,了解更多相关信息:
Storing Objects in HTML5 localStorage 在HTML5 localStorage中存储对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.