2012-03-17 34 views
2

我有一個骨幹集合,只要另一個骨幹模型(沒有集合的一部分)改變就需要獲取。Backbone.js在觸發器回調綁定不能按預期工作

當我寫這樣的:

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

這是一個有趣的嘗試和解釋:)

所以,當你調用on這樣的:

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

你設置的是fetch在運行任何this是上下文。在此代碼中,它看起來像this只是您的頂級應用程序或類似的。 fetch不能做太多!讓我們來看看fetch實現:

// 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); 
}, 

所以我們基本上使之達到var collection = this; ... 糟糕!

我們已將collection設置在fetch之內成爲您的頂級應用!


所以,當你把它包裝它的工作原理的原因是更有趣:

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

我們設定的wrapped上下文是this。這很好,因爲this.bCollection正是我們想要的。但是當你在bCollection這裏調用fetch時,它是以正常的方式進行的,在它內部綁定this到它被調用的對象 - 這是現在正常的javascript東西。


所以,這裏有一個TL; DR:

你真的想:

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

因爲fetch函數調用的情況下應該是集合本身,而不是其他。

有意義嗎?

乾杯:)

+0

優秀的解釋。非常感謝! – MrJ 2012-03-19 03:24:35

+0

很高興幫助! – rfunduk 2012-03-19 13:18:46