1

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.

Adam Moss
  • 5,582
  • 13
  • 46
  • 64

2 Answers2

1

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

});
user3508122
  • 664
  • 3
  • 10
1

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

});
Ravi Hamsa
  • 4,721
  • 3
  • 14
  • 14