将模型保存在本地存储中
我正在使用 Jerome 的 localStorage 适配器与 Backbone,它非常适合集合。
但是,现在我需要保存一个模型。所以在我的模型中我设置:
localStorage: new Store("msg")
然后我进行保存并获取。我的问题是,每次刷新并初始化我的应用程序时,我的模型的新表示都会添加到 localStorage 中,请参见下文。
我做错了什么?
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'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"
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我遇到了同样的问题。也许您有类似的东西,
我更改为
localStorage 适配器检查 id,例如
0
或""
for id 不起作用,它将返回一个中的所有模型I ran into same issue. Maybe you have something similar to this
I changed to
localStorage adapter check for id like
so
0
or""
for id wont work and it will return all models in one我对backbone.js 也是新手,但看起来持久性模型类似于数据库表。也就是说,它旨在从表中创建/删除/读取记录。 localStorage 适配器执行相同的操作,因此您要做的是创建一个 Msg“表”
在 localStorage 中,每次创建一个新的 Msg“记录”,并且适配器为每个新的 Msg 提供一个唯一的 id。
如果您只有一个对象,那么直接使用 localStorage 可能会更容易。 API 非常简单:
请记住,localStorage 仅将键/值对作为字符串处理,因此您需要在字符串格式之间进行转换。
看看这个问题,了解更多相关信息:
在 HTML5 localStorage 中存储对象
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:
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