为什么我的主干集合包含一个空的模型项

Why does my backbone collection contain an empty model item?

本文关键字:模型 包含一 我的 集合 为什么      更新时间:2023-09-26

我有一个游戏模型,其记分卡属性是一个集合。我正在嵌套这个集合,所以当我初始化时,我使用 nestCollection 来创建更改处理程序,以保持所有内容更新和同步。每当我创建新的游戏模型时,都会将一个空模型添加到记分卡属性集合中,但仅在内存中 - 保存到本地存储的内容是正确的。我不知道为什么。

这是我的游戏模型定义 - 请注意控制台日志语句结果

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);
}

你的问题来自这段代码:

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

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

所以基本上,this.get('scorecards'))被强制转换为Scorecard(或任何你的模型被称为),这就是为什么你有一个空模型。

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