在本地存储中保存模型 [英] Saving a model in local storage
问题描述
我将 Jerome 的 localStorage 适配器与 Backbone 一起使用,它非常适合收藏.
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")
然后我会保存并获取.我的问题是,每次我刷新并初始化我的应用程序时,我的模型的新表示都会添加到 localStorage,见下文.
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.
我做错了什么?
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();
我改成
var s = new Settings({ id: 1 });
localStorage 适配器检查 id 之类的
localStorage adapter check for id like
case "read": resp = model.id ? store.find(model) : store.findAll(); break;
so 0
或 ""
id 不起作用,它将返回所有模型
so 0
or ""
for id wont work and it will return all models in one
这篇关于在本地存储中保存模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!