2012-06-29 1 views
6

Backbone.RelationalModelのインスタンスである2つのモデル(ユーザーとタスク)があります。_.bindAllとUncaught TypeError:backbone-relation.jsで未定義のプロパティ 'idAttribute'を読み取ることができません

これら二つのモデルについての関係以下の通りです:私はFollowerCollection私にフェッチ作るとき

var FollowerCollection = Backbone.Collection.extend({ 
    initialize: function() { 
     _.bindAll(this); 
    } 
    model: User 
}); 


var User = Backbone.RelationalModel.extend({ 

}); 

:その後、私はこのようなコードのコレクションを持っている

// Task model 

    var Task = Backbone.RelationalModel.extend({ 

     relations: [ 
      { 
       type: 'HasOne', 
       key: 'user', 
       relatedModel: User 
      } 
     ], 

     urlRoot: 'someUrl' 

    }); 

次のエラーが表示されます。

Uncaught TypeError: Cannot read property 'idAttribute' of undefined 
ここ backbone-relation version 0.5.0


の骨格relation.jsバックボーン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)に関連してのライン1565に

私はそれをコメントする、それは適切に動作します。
なぜですか?何か案は?


+0

関係を宣言するときに定義された 'User'モデルは本当ですか? –

+0

@mashinganタスクモデルについてすべてのコードを添付しました。あなたは見ていただけますか?ありがとう。 –

+0

FollowerCollectionとUserのコードを添付して問題を見つけることさえできますか?現在、私は2つのクラスの間に何の関係も見ません。 – jakee

答えて

3

_.bindAllを削除すると機能しません。

本当に便利な機能なので、残念です。それはバックボーンのある部分とひどくやりとりする必要があります。私は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で失敗しました。何? Y A。本当のために。

_.bindAllが呼び出されると、@ jakeeのように、コレクションのすべてのプロパティがバインドされるという問題があります。これにはCollection.modelが含まれているようですが、これは私が思うバグです。

解決策は、これが固定されるまで個々の方法を結合することです。

githubには既存の、しかし閉鎖された問題があります:https://github.com/documentcloud/backbone/issues/2080 現在のメンテナーがこのメソッドを気に入らないようですが、その理由はわかりません。

0

私のプロジェクトが本当に大きくて、自分のカスタムbindAllを作成する必要がありました。ここにはコードがあり、最新のバージョンで動作します。 このようなプロパティを持つプロトタイプを持つもの以外のインスタンス "this"のすべてのプロパティをバインドします。コレクションモデル

https://gist.github.com/patrixd/8025952

//bindAll from underscore that allows 1 argument to bind all the functions from the prototype, 
//or if there are more arguments they will be the only binded 
_.originalBindAll = _.bindAll; 
_.bindAll = function (that) { 
     var funcs = Array.prototype.slice.call(arguments, 1), 
      validKeys = [], fn; 
     if (funcs.length == 0) { 
     for (var i in that) { 
      fn = that[i]; 
      if (fn && typeof fn == "function" && (!fn.prototype ||   
       _.keys(fn.prototype).length == 0)) 
       validKeys.push(i); 
    } 
    _.originalBindAll.apply(_, [that].concat(validKeys)); 
} 
else 
    _.originalBindAll.apply(_, arguments); 

}。

関連する問題