zero
zero

Reputation: 1107

Backbone scope of window instead of this

Why is this logging as window instead of the Backbone object?

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
    }
});

Upvotes: 1

Views: 337

Answers (3)

Ronan
Ronan

Reputation: 1512

"this" in the success attribute of your fetch function is not in your backbone view scope anymore. A workaround is to add a

var that = this;

And use "that" in your fetch success attribute like below:

var that = this;
this.fetch({success: that.success});

Upvotes: 0

Sandro Munda
Sandro Munda

Reputation: 41030

Because you need to bind this in your initialize function like that:

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
    }
});

Upvotes: 0

Prinzhorn
Prinzhorn

Reputation: 22508

Because the function is called by jQuery's (or whichever DOM lib you use) ajax function.

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

Upvotes: 2

Related Questions