Javascript 而不是此窗口的主干范围
为什么将此日志记录为窗口而不是主干对象Javascript 而不是此窗口的主干范围,javascript,backbone.js,scope,Javascript,Backbone.js,Scope,为什么将此日志记录为窗口而不是主干对象 App.Models.Site = Backbone.Model.extend({ url: 'assets/json/app.json', initialize: function(){ this.fetch({success:this.success}); }, success: function(){ console.log('success', this.attributes);
App.Models.Site = Backbone.Model.extend({
url: 'assets/json/app.json',
initialize: function(){
this.fetch({success:this.success});
},
success: function(){
console.log('success', this.attributes); // log's: success undefined
console.log(this); // window
}
});
因为该函数是由jQuery(或您使用的任何DOM库)调用的
ajax
函数
使用
this.fetch({success:\.bind(this.success,this)})代码>,因为您需要在初始化函数中绑定此
,如下所示:
App.Models.Site = Backbone.Model.extend({
url: 'assets/json/app.json',
initialize: function(){
_.bindAll(this, 'success'); // Ensure the 'success' method has the correct 'this'
this.fetch({success:this.success});
},
success: function(){
console.log('success', this.attributes);
console.log(this); // this is now correctly set
}
});
fetch函数的success属性中的“this”不再在主干视图范围内。解决方法是添加
var that = this;
并在获取成功属性中使用“that”,如下所示:
var that = this;
this.fetch({success: that.success});
通常,您可以将上下文作为参数传递:,但在
这种情况下不可以。不完全是这样,主干网在您和jQuery之间放置了一个成功处理程序,该成功处理程序调用传递给的fetch
,因此主干网特定的参数:。