为什么我的主干集合包含一个空的模型项
Why does my backbone collection contain an empty model item?
我有一个游戏模型,其记分卡属性是一个集合。我正在嵌套这个集合,所以当我初始化时,我使用 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
(或任何你的模型被称为),这就是为什么你有一个空模型。
将参数传递给构造函数的目的与创建集合的目的不同是一个坏主意,之后应该调用一个方法。
相关文章:
- 预期响应包含一个对象,但在angular js中得到一个数组错误
- 重定向到同一页面,但其中包含一条消息
- 重定向到同一页面,但其中包含一条消息
- 如何只包含一次javascript文件
- 响应字段包含一个子级时的节点 SOAP 强制数组
- 多个模型成一条路由并过滤 Ember 选择
- 如何使用bower在javascript项目中包含一个私有的本地文件
- 使用moment js创建一个包含一周中的几天和一天中的几个小时的数组
- 如何检查对象是否包含一组属性
- 如果模型包含使用findWhere存在的键,则返回主干模型
- 如何判断一个对象是否包含一个数组
- Js-data在一条路由中包含多个模型
- 如何在asp.net中使用Javascript从gridview中搜索仅包含一列
- jQuery -检查val是否为空并包含一段特定的文本
- 在$scope模型的一个数组下,ng-repeat: collect状态创建的按钮列表
- 如何确保javascript在ASCX中使用时只包含一次
- 拆分数组仍然是一个包含一项的数组,而不是字符串
- 对象的Javascript数组,其中一个对象还包含一个数组
- Jquery函数只包含一次
- 基于下拉列表中设置的初始值,用Javascript在表单中填充6个字段,其中包含一周中的天数