我有一个带有记分卡属性的游戏模型,它是一个集合。我正在嵌套这个集合,所以当我初始化时,我使用nestCollection 创建更改处理程序以保持所有内容的更新和同步。每当我创建一个新的游戏模型时,都会将一个空模型添加到记分卡属性集合中,但仅在内存中 - 保存到 localstorage 的内容是正确的。我不知道为什么。
这是我的游戏模型定义-注意控制台日志语句结果:
var Game = Backbone.Model.extend({
localStorage: new Backbone.LocalStorage('datastore'),
defaults: {
name : '',
scorecards: new ScorecardList(),
created : 0
},
initialize : function() {
console.log(this.scorecards); // prints undefined
console.log(this.get('scorecards')); // length is 0 as expected
this.scorecards = nestCollection(this, 'scorecards', new ScorecardList(this.get('scorecards')));
console.log(this.scorecards); // length is 1, with empty element in it
console.log(this.get('scorecards')); // length is 0 as expected
if (this.isNew()) this.set('created', Date.now());
}
});
嵌套代码:
function nestCollection(model, attributeName, nestedCollection) {
//setup nested references
for (var i = 0; i < nestedCollection.length; i++) {
model.attributes[attributeName][i] = nestedCollection.at(i).attributes;
}
//create empty arrays if none
nestedCollection.bind('add', function (initiative) {
if (!model.get(attributeName)) {
model.attributes[attributeName] = [];
}
model.get(attributeName).push(initiative.attributes);
});
nestedCollection.bind('remove', function (initiative) {
var updateObj = {};
updateObj[attributeName] = _.without(model.get(attributeName), initiative.attributes);
model.set(updateObj);
});
return nestedCollection;
}
这是我用来创建新游戏的代码:
addGame: function () {
var g = new Game({
name:this.ui.gameName.val()
});
app.gameList.create(g,{wait:true});
//Backbone.history.navigate('game/new/'+ g.id, true);
}