javascript 在本地存储中保存模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7544503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving a model in local storage
提问by Sebastian
I'm using Jerome's localStorageadapter 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"
}
}
回答by Igor Alekseev
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
so 0
or ""
for id 不起作用,它会将所有模型合二为一
回答by vihacker
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.
我也是backbone.js 的新手,但看起来持久性模型类似于数据库表。也就是说,它旨在从表中创建/删除/读取记录。localStorage 适配器做同样的事情,所以你在那里做的是在 localStorage 中创建一个 Msg “表”,并且每次创建一个新的 Msg “记录”,并且适配器给每个新的 Msg 一个唯一的 id。
If you just have one object, it's probably easier to just use localStorage directly. The API is really straight forward:
如果您只有一个对象,直接使用 localStorage 可能更容易。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:
看看这个问题,了解更多关于这样做的信息: