【发布时间】:2014-12-24 17:35:39
【问题描述】:
我正在尝试实现嵌套集合,就像我在此处找到的示例一样:https://stackoverflow.com/a/17453870/295133
唯一的区别是我尝试使用 localStorage 插件在本地存储数据。
在这里,我的列表将是上面示例中的酒店:
var app = app || {};
(function (){
'use strict';
// List Collection - list of words
//---------------------
var listCollection = Backbone.Collection.extend({
//referebce to this collection's model
model: app.ListModel,
localStorage: new Backbone.LocalStorage('translate-lists')
});
app.listCollection = new listCollection();
})();
(function (){
'use strict';
app.ListModel = Backbone.Model.extend({
initialize: function() {
// because initialize is called after parse
_.defaults(this, {
words: new app.wordCollection
});
},
parse: function(response) {
if (_.has(response, "words")) {
this.words = new app.wordCollection(response.words, {
parse: true
});
delete response.words;
}
return response;
}
});
})();
localStorage 的作用是存储 ListModel,但如果我在 words 集合中添加任何内容,刷新后它很快就会消失。
任何想法我应该如何保存整个嵌套集合?
【问题讨论】:
-
我刚刚意识到,也许我正忙于尝试学习 Backbone,我让事情变得过于复杂。 Backbone 自己说他们不直接支持嵌套。我不能有两个单独的集合并使用标识符匹配内容吗?
-
您是否还需要为单词集合设置本地存储?
-
我试过了,但它不起作用。 _.has(response,'words') 的 parse 方法永远不会触发 true。也许这可能与它有关。
-
我不记得了,但是主干本地存储是否使用
model.toJSON()方法来存储模型?如果是这样,您是否检查过 words 集合中的模型是否已存储?如果他们不是,我想我知道原因并且可能有一个修复 -
我会调查的。为什么 listmodels 会被存储而不是 wordmodel?
标签: javascript backbone.js backbone-local-storage