2012-03-17 1 views
2

私は、バックボーンコレクションがあります。これは、別のバックボーンモデル(コレクションの一部)が変更されたときにフェッチする必要があります。Backbone.js Onトリガコールバックバインディングが期待通りに動作しない

私はこのようにそれを書くとき:

this.fModel = new FooModel(); 
this.bCollection = new BarCollection(); 
this.fModel.on("change", this.bCollection.fetch, this) 

変更イベントがトリガされたとき、私は次のエラーを取得する:

Uncaught TypeError: Object #<Object> has no method 'trigger' 

しかし、私は単にそれが動作しますが、コレクションの呼び出しフェッチを包むとき期待通り:

this.fModel = new FooModel(); 
this.bCollection = new BarCollection(); 
this.testfunc = function(){ 
    this.bCollection.fetch(); 
} 
this.fModel.on("change", this.testfunc, this) 

なぜこの場合ですか?ありがとう!

答えて

6

これは、1つは試してみて、説明するのも楽しいです:)

あなたはこのようonを呼び出すときに:

this.fModel.on('change', this.bCollection.fetch, this); 

あなたはfetchがどんなthisであるにして実行されていることをコンテキストを設定しています。このコードでは、thisは単純にトップレベルのアプリケーションまたは類似のものです。 fetchはそれほどできません!だから私たちは基本的にvar collection = this;にそれを作る

// Fetch the default set of models for this collection, resetting the 
// collection when they arrive. If `add: true` is passed, appends the 
// models to the collection instead of resetting. 
fetch: function(options) { 
    options = options ? _.clone(options) : {}; 
    if (options.parse === undefined) options.parse = true; 
    var collection = this; 
    var success = options.success; 
    options.success = function(resp, status, xhr) { 
    collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options); 
    if (success) success(collection, resp); 
    }; 
    options.error = Backbone.wrapError(options.error, collection, options); 
    return (this.sync || Backbone.sync).call(this, 'read', this, options); 
}, 

... おっと:さんはfetchの実装を見てみましょう!

fetchに設定しました。トップレベルのアプリケーションに設定しました。


だから、あなたはそれをラップするとき、それは働く理由はもっと楽しいです:

var wrapped = function() { this.bCollection.fetch(); }; 
this.fModel.on('change', wrapped, this); 

我々はthisするwrappedのコンテキストを設定しました。 this.bCollectionはまさに私たちが望むものなので、それは問題ありません。しかし、ここでをbCollectionと呼ぶと、普通のやり方で、その中にthisというオブジェクトがバインドされています。これは通常のjavascriptのものです。


だから、ここTLです; DR:

あなたが実際にしたい:

this.fModel.on('change', this.bCollection.fetch, this.bCollection); 

fetch関数呼び出しのコンテキストはコレクション自体、そして他には何もする必要がありますので。

意味がありますか?

乾杯:

+0

優秀な説明。本当にありがとう! – MrJ

+0

うれしかった! – rfunduk

関連する問題