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 関数の success 属性の「this」は、バックボーン ビュー スコープにはもうありません。回避策は、

var that = this;

そして、以下のようにフェッチ成功属性で「それ」を使用します。

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 に答える