Lor*_*ard 6 backbone.js backbone-relational
我有两个模型(用户和任务),它们是实例Backbone.RelationalModel.
这两个模型的关系如下:
// Task model
var Task = Backbone.RelationalModel.extend({
relations: [
{
type: 'HasOne',
key: 'user',
relatedModel: User
}
],
urlRoot: 'someUrl'
});
Run Code Online (Sandbox Code Playgroud)
然后我有一个代码看起来像这样的集合:
var FollowerCollection = Backbone.Collection.extend({
initialize: function () {
_.bindAll(this);
}
model: User
});
var User = Backbone.RelationalModel.extend({
});
Run Code Online (Sandbox Code Playgroud)
当我在FollowerCollection上进行提取时,我收到以下错误:
Uncaught TypeError: Cannot read property 'idAttribute' of undefined
Run Code Online (Sandbox Code Playgroud)
在骨干关系的1565行 backbone-relation version 0.5.0
这里是一段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 ] );
Run Code Online (Sandbox Code Playgroud)
问题是_.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];
},
Run Code Online (Sandbox Code Playgroud)
this.model.prototype由于原型未定义,代码失败。什么?是啊。真的。
问题是,当调用 _.bindAll 时,它会绑定集合的所有属性,正如 @jakee 所说。这似乎包括 Collection.model,我认为这是一个错误。
解决方案是绑定各个方法,直到问题得到解决。
github 上有一个现有但已关闭的问题: https: //github.com/documentcloud/backbone/issues/2080 似乎当前的维护者不喜欢该方法,但我不明白为什么。
| 归档时间: |
|
| 查看次数: |
3035 次 |
| 最近记录: |