尝试从值列表中填充集合,我收到有关集合的model
prototype
未定义的错误。 查看有关类似问题的问题,我已经尽我所能检查了模型是否在实例化集合之前实际创建。
在从服务器获取数据并尝试使用应填充到集合中的数据中的值列表reset
集合后,在保存集合的木偶复合视图的事件处理程序之一中抛出错误。
注意:使用主干 0.9.10
模型
MyItemModel = Backbone.Model.extend({});
收藏
MyCollection = Backbone.Collection.extend({
model: MyItemModel
});
复合视图的相关代码
MyCompositeView = Backbone.Marionette.CompositeView.extend({
initialize: function(options) {
_.bindAll(this);
this.model = new MyCompositeViewModel();
this.collection = new MyCollection();
},
//This event handler gets properly fired and run.
on_event: function() {
var that = this;
// The data comes through fine with this `fetch`
this.model.fetch({success: function() {
var collection_results= that.model.get("collection_results");
// The error fires in this line
that.collection.reset(collection_results);
that.render();
});
}
})
错误
错误发生在 Backbone 中的add
函数中,当对模型对象执行get
时,检查它是否重复。 失败的代码在这里:
// Get a model from the set by id.
get: function(obj) {
if (obj == null) return void 0;
// The error originates from this line
this._idAttr || (this._idAttr = this.model.prototype.idAttribute);
return this._byId[obj.id || obj.cid || obj[this._idAttr] || obj];
},
this._idAttr || (this._idAttr = this.model.prototype.idAttribute);
在这里,this.model.prototype.idAttribute
失败,因为未定义模型的prototype
。
为什么会发生这种情况,如何解决?
多谢!
原因是,在 Babkbone 0.9.10 中,如果你调用没有选项的collection.reset(models)
,模型将被传递给严格需要真实模型作为参数的collection.add()
。
但是,事实上,你通过的论点并不是真实的模型。它们只是一个哈希属性数组。
要修复的两个选项:
选项1:使用解析选项调用重置
that.collection.reset(collection_results, {parse: true});
然后reset
将解析哈希数组并将它们设置为模型。
选项 2:升级到最新版本的主干 1.1.0。
在这里,reset()
不再将责任推给add()
,而是巧妙地使用set()
。建议使用此选项。而且您在这里不需要选项。
that.collection.reset(collection_results)
另一点
我可以建议你不要在复合视图中定义model
吗?复合视图用于收集,而不是模型。当然,我知道这里的模型只是为了保存和获取一些数据,但是如果代码被另一个开发人员以及您自己的维护来读取,那将非常令人困惑。
要获取引导数据,您可以在第一次请求时加载数据,并使用常规方式将其放入集合中。 http://backbonejs.org/#FAQ-bootstrap