使用 Backbone (1.2.3),我尝试使用集合的 model
property 来使用多个模型构建集合。 :
var coll = Backbone.Collection.extend({
model: function(attrs, options) {
switch(attrs.type) {
case 'type-a':
return new BackboneModelA(attrs, options);
case 'type-b':
return new BackboneModelB(attrs, options);
}
},
modelId: function(attrs) {
return attrs.type + ':' + attrs.id;
}
});
new coll([
{type: 'type-a', id: 1}
]);
但它抛出一个错误:
TypeError: Cannot read property 'type' of undefined(…)
实际上,modelId()
被调用了两次,而第二次,attrs
是未定义
。
PS:我知道它与此完全重复:Backbone Collection with multiple models?但我在那里没有找到任何有用的东西。
最佳答案
modelId
1.2.3 支持。
第一次调用 modelId
时,它位于集合 get
函数的 969 行中。 :
var id = this.modelId(this._isModel(obj) ? obj.attributes : obj);
此时,obj
为 {type: 'type-a', id: 1}
并且它被发送到 modelId
作为-是。
第二次调用 modelId
时,它位于集合 _addReference
函数中,第 1126 行:
var id = this.modelId(model.attributes);
这意味着此时,model
不是 Backbone 模型,并且 model.attributes
未定义。
如果没有 BackboneModelA
的代码,我们将无法为您提供进一步帮助,但您应该查看它并确保它扩展了 Backbone.Model
。
关于javascript - 无法使用不同模型读取未定义的 Backbone 集合的属性 'type',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39493309/