将模型保存在本地存储中 [英] Saving a model in local storage
问题描述
我正在使用带有Backbone的 Jerome的localStorage 适配器,它非常适合收藏。
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;
所以 0
或因为id无法正常工作,它将返回所有模型中的一个
so 0
or ""
for id wont work and it will return all models in one
这篇关于将模型保存在本地存储中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!