だから私はこのようなjavascript/Backboneスクリプトを持っています:
var Model = Backbone.Model.extend({});
var View = Backbone.View.extend({
initialize: function() {
_.bindAll(this); //bind this
this.doProcessing();
},
doProcessing: function() {
$('.someElement').each(function() {
Model myModel = new Model;
myModel.fetch({ //issue ajax
success: function(model, response){ //after successful ajax
console.log(this) // <-- outputs Window!!
});
}); //end each
} //end processing
});
new View;
私を逃れるのは、どのようthis
にしてウィンドウにバインドされるかです。私は自分のクロージャをよく知っていますが、 ?this
を参照するべきではありません。model
これが私が理解していることです-成功のコールバックはどういうわけかウィンドウオブジェクトにバインドされています。したがって、呼び出されたときのコンテキストは、ウィンドウオブジェクトのコンテキストです。しかし、私の意見では、それは少し予想外の動作です。バックボーンがそれを行う理由(または私が何かを誤解しているのですか?)
のパラメータを使用myModel
してのプロパティを設定するのは少し奇妙です。単純なものを許可する必要があるときに呼び出すのはかなり複雑なようですmodel
success
model.set({...})
this.set({...})
この場合、私の理解はthis
正しいですか?回避策はありますか?それとも、これはXHRが成功コールバックにバインドする方法の多くですか?
バックボーンのソース(Model.fetch)から:
fetch: function(options) {
options = options ? _.clone(options) : {}; //cloning options - does this variable get bound to global?
var model = this;
var success = options.success; //or is it this?
options.success = function(resp, status, xhr) {
if (!model.set(model.parse(resp, xhr), options)) return false;
if (success) success(model, resp);
};
options.error = Backbone.wrapError(options.error, model, options);
return (this.sync || Backbone.sync).call(this, 'read', this, options);
},