为什么我的骨干集合包含空模型项?

时间:2013-09-15 13:07:04

标签: javascript backbone.js marionette

我有一个带有记分卡属性的游戏模型,它是一个集合。我正在嵌套这个集合所以当我初始化时,我正在使用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);
}

1 个答案:

答案 0 :(得分:3)

你的问题来自这段代码:

new ScorecardList(this.get('scorecards'))

这里你给你的ScorecardList构造函数另一个集合作为参数。这个集合恰好是一个对象。因此,您的集合的构造函数会认为它是您创建模型的对象。

所以基本上,this.get('scorecards'))会被转换为Scorecard(或者你的模型被称为),这就是你有一个空模型的原因。

为了与创建集合不同的目的将参数传递给构造函数是一个坏主意,之后应该调用一个方法。

相关问题