這是一個有趣的嘗試和解釋:)
所以,當你調用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
函數調用的情況下應該是集合本身,而不是其他。
有意義嗎?
乾杯:)
優秀的解釋。非常感謝! – MrJ 2012-03-19 03:24:35
很高興幫助! – rfunduk 2012-03-19 13:18:46