gpt4 book ai didi

javascript - 为什么我的主干集合包含空模型项?

转载 作者:行者123 更新时间:2023-11-28 20:18:23 24 4
gpt4 key购买 nike

我有一个游戏模型,其记分卡属性是一个集合。我正在嵌套此集合,因此当我初始化时,我使用 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 (或任何你的模型被称为),这就是为什么你有一个空的型号。

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

关于javascript - 为什么我的主干集合包含空模型项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18812731/

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