gpt4 book ai didi

javascript - 在嵌套集合上使用 Backbone localStorage

转载 作者:行者123 更新时间:2023-11-28 07:52:19 25 4
gpt4 key购买 nike

我正在尝试实现嵌套集合,就像我在这里找到的示例一样: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 的作用是存储 ListModels,但是如果我向单词集合中添加任何内容,它在刷新后很快就会消失。

有什么想法我应该如何保存整个嵌套集合?

最佳答案

因此,让这个工作正常进行,它归结为解析中的某些内容,但如果您想确保只是从嵌套集合中获取属性,则应该覆盖 toJSON,否则您将在返回的内容中获得完整的集合。

  Backbone.Model.prototype.toJSON = function() {
var json = _.clone(this.attributes);
for (var attr in json) {
if ((json[attr] instanceof Backbone.Model) || (json[attr] instanceof Backbone.Collection)) {
json[attr] = json[attr].toJSON();
}
}
return json;
};

主要的问题在于解析。是将单词直接分配给模型,

this.words = new app.wordCollection(response.words, {
parse: true
});

但这意味着当调用 toJSON 时它不会显示,因为它不在属性中(这也意味着您无法通过 model.get 访问它)

所以应该改为

initialize: function () {
// because initialize is called after parse
_.defaults(this.attributes, {
words: new app.WordCollection()
});
},
parse: function (response) {
if (_.has(response, "words")) {
this.attributes.words = new app.WordCollection(response.words, {
parse: true
});
delete response.words;
}
return response;
}

这样它就被添加到模型的属性中,而不是直接添加到模型上。如果你看这个 fiddle http://jsfiddle.net/leighking2/t2qcc7my/并继续点击运行,它将在集合中创建一个新模型,将其保存在本地存储中,然后将结果打印到控制台。每次您点击运行时,您应该会看到它增加 1(因为它获取了本地存储中的先前结果)并包含您想要的完整信息。

关于javascript - 在嵌套集合上使用 Backbone localStorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26623163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com