为什么这个日志记录是窗口而不是Backbone对象?
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
}
});
答案 0 :(得分:2)
因为该函数是由jQuery(或您使用的任何DOM库)ajax
函数调用的。
使用this.fetch({success:_.bind(this.success, this)});
答案 1 :(得分:0)
因为您需要在初始化函数中绑定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
}
});
答案 2 :(得分:0)
var that = this;
在你的获取成功属性中使用“that”,如下所示:
var that = this;
this.fetch({success: that.success});