【发布时间】:2016-11-26 13:41:52
【问题描述】:
在我的项目中,我使用 Backbone 集合来排列应用程序的数据,并且我还需要将我的数据同步到本地存储。我的数据是一个两级深度嵌套的集合和模型,这就是问题所在。
内部集合同步到localstorage后,就变成了对象的原始数组。所以不能使用收集方式(如add)。
经过调试和谷歌搜索,我找到了原因:
localStorage 序列化模型时,它调用model.toJSON(),它只是克隆模型的属性,不包括嵌套集合。
// Return a copy of the model's `attributes` object.
toJSON: function(options) {
return _.clone(this.attributes);
},
所以它使用Underscore's clone function,并且文档说它:
创建提供的普通对象的浅拷贝克隆。任何嵌套 对象或数组将通过引用复制,而不是复制。
所以我正在寻找一种深拷贝方法来覆盖默认模型的.toJSON。但我想不出正确的方法。
例如,我尝试了以下方法:
Backbone.Model.prototype.toJSON = function() {
var json = $.extend(true, {}, this.attributes);
return json;
};
编辑,根据 Emile 的建议,我的真实模型如下:
app.RecordItem = Backbone.Model.extend({
defaults: {
target: 1,
date: '',
day: '',
//foodlist: new TrackList(),
currentvalue: 0,
isSetup: false,
},
initialize: function() {
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var d = new Date();
this.set("date", d.getDate() + "." + months[d.getMonth()]);
this.set("day", days[d.getDay()]);
//
var foodlist = this.getFoodlist();
if (!(foodlist instanceof TrackList)) {
this.set('foodlist', new TrackList(foodlist));
}
},
getFoodlist: function() {
if (!this.foodlist) this.foodlist = new TrackList(this.get('foodlist'));
return this.get('foodlist');
},
toJSON: function(options) {
// this gets the default behavior
var attrs = this.constructor.__super__.toJSON.apply(this, arguments);
var foodlist = attrs.foodlist;
if (foodlist) {
// then replace the collection reference with the actual serialized data
attrs.foodlist = foodlist.toJSON(options);
}
return attrs;
},
});
在覆盖toJSON 方法之后。错误信息是
"foodlist.toJSON is not a function(…)"
【问题讨论】:
标签: javascript backbone.js nested backbone.js-collections