Adam Moss
Adam Moss

Reputation: 5712

Backbone JS: Assign a model attribute in fetch call

Sorry, if this is basic but I'm a total starter with Backbone.js and I can't work out how to simply assign an attribute (data) with data obtained from fetch. I believe it's to do with binding (this), but I can't figure it out. Here's my code:

var form_model = Backbone.Model.extend({ 
    urlRoot: QuoteForm.ajaxurl,
    data: "",

    initialize: function()
    {
        this.fetch({
            data: { action: 'quote_form_data' },
            success: function (response) {
                // this bit won't assign
                this.data = response.toJSON();
            }
        });
    }   

    });

When I console.log() the returned data it is correct, however I cannot assign it and use the data attribute in my view. Please help.

Upvotes: 1

Views: 412

Answers (2)

Ravi Hamsa
Ravi Hamsa

Reputation: 4721

More reader friendly version would be

var form_model = Backbone.Model.extend({
    urlRoot: QuoteForm.ajaxurl,
    data: "",

    initialize: function () {
        var _this = this;
        this.fetch({
            data: { action: 'quote_form_data' },
            success: function (response) {
                // more reader freindly version would be;
                _this.data = response.toJSON();
            }
        });
    }

});

Upvotes: 1

user3508122
user3508122

Reputation: 674

Edit: without binding, the this pointer in the success callback points to the window object

var form_model = Backbone.Model.extend({ 
urlRoot: QuoteForm.ajaxurl,
data: "",

initialize: function()
{
    this.fetch({
        data: { action: 'quote_form_data' },
        success: function (response) {
            // this bit won't assign
            this.data = response.toJSON();
        }.bind(this)
    });
}   

});

Binding to this will set the this pointer correctly, the native .bind method only works in EMCAScript 5 browsers and above. Due to backbone depending on Underscore JS, you could do this instead for extra compatibility

var form_model = Backbone.Model.extend({ 
urlRoot: QuoteForm.ajaxurl,
data: "",

initialize: function()
{
    this.fetch({
        data: { action: 'quote_form_data' },
        success: _.bind(function (response) {
            // this bit won't assign
            this.data = response.toJSON();
        }, this)
    });
}   

});

Upvotes: 1

Related Questions