我有两个模型(用户和任务),它们是 Backbone.RelationalModel
的实例.
这两个模型的关系如下:
// Task model
var Task = Backbone.RelationalModel.extend({
relations: [
{
type: 'HasOne',
key: 'user',
relatedModel: User
}
],
urlRoot: 'someUrl'
});
然后我有一个集合,其代码如下所示:
var FollowerCollection = Backbone.Collection.extend({
initialize: function () {
_.bindAll(this);
}
model: User
});
var User = Backbone.RelationalModel.extend({
});
当我在 FollowerCollection 上进行提取时,出现以下错误:
Uncaught TypeError: Cannot read property 'idAttribute' of undefined
在
backbone-relation version 0.5.0
的主干关系.js 的第 1565 行这里有一段backbone-relation.js的代码
if ( !( model instanceof Backbone.Model ) ) {
// Try to find 'model' in Backbone.store. If it already exists, set the new properties on it.
var existingModel = Backbone.Relational.store.find( this.model, model[ this.model.prototype.idAttribute ] );
问题与
_.bindAll(this)
有关因为如果我评论它,它会正常工作。为什么?有任何想法吗?
最佳答案
删除 _.bindAll 确实有效。
很遗憾,因为它是一个非常方便的功能。它必须与 Backbone 的某些部分严重交互。我在 v9.10
我一直使用这种方法,但有时只会出现问题(比如当你想批量添加到集合中时)。
对我来说,问题出在这个 Backbone.js 方法中:
// Get a model from the set by id.
get: function(obj) {
if (obj == null) return void 0;
this._idAttr || (this._idAttr = this.model.prototype.idAttribute);
return this._byId[obj.id || obj.cid || obj[this._idAttr] || obj];
},
代码在
this.model.prototype
处失败因为原型(prototype)是未定义的。什么?是的。真的。问题是当 _.bindAll 被调用时,它会绑定(bind)集合的所有属性,正如@jakee 所说。这似乎包括 Collection.model,我认为这是一个错误。
解决方案是绑定(bind)各个方法,直到解决此问题。
github 上有一个现有但已关闭的问题:https://github.com/documentcloud/backbone/issues/2080
似乎当前的维护者不喜欢这种方法,但我不明白为什么。
关于backbone.js - _.bindAll(this) 和 Uncaught TypeError : Cannot read property 'idAttribute' of undefined in backbone-relation. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11259720/