【发布时间】:2012-08-04 04:02:44
【问题描述】:
所以我有这个看起来像这样的 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 吗?
这就是我的理解 - 成功回调以某种方式绑定到 Window 对象。因此,当它被调用时,上下文就是窗口对象的上下文。但在我看来,这有点出乎意料。骨干为什么这样做的任何原因(或者我误解了什么?)。
通过success的model参数设置myModel的属性有点奇怪。当它应该允许一个简单的this.set({...}) 时,调用model.set({...}) 似乎很复杂
在这种情况下,我对this 的理解是否正确?任何解决方法?或者这更像是 XHR 绑定到成功回调的方式?
来自 Backbone 的源代码 (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);
},
【问题讨论】:
标签: javascript ajax backbone.js closures this