1

为什么此日志记录为窗口而不是 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
    }
});
4

3 回答 3

2

因为该函数是由 jQuery(或您使用的任何 DOM 库)ajax函数调用的。

利用this.fetch({success:_.bind(this.success, this)});

于 2013-02-18T12:57:54.027 回答
0

fetch 函数的成功属性中的“this”不再位于主干视图范围内。一种解决方法是添加一个

var that = this;

并在您的获取成功属性中使用“that”,如下所示:

var that = this;
this.fetch({success: that.success});
于 2013-02-18T15:03:58.277 回答
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
    }
});
于 2013-02-18T12:58:19.393 回答