Evan
Evan

Reputation: 456

Problems using backbone this.set from within a callback

I'm trying to set my backbone model's parameter from within a callback, but I continue to get the error "this.set is not a function." I thought _.bindAll was intended to resolve these scenarios...am I using it wrong? Is there a different approach I can use to make sure I'm not setting the model's status parameter until after the callback has fired?

var Service = Backbone.Model.extend({
    defaults : {
        status : "off"
    },
    url : "/status",
    initialize : function {
        _.bindAll(this, "getStatus");
        this.getStatus();
    },
    getStatus : function() {
        $.getJSON(this.url(), function(data) {
            this.set({status : data.status});
        }); 
    }
});

Upvotes: 1

Views: 1473

Answers (1)

Colin Brock
Colin Brock

Reputation: 21565

this does not refer to your model within the context of your .getJSON callback. You can save a reference to your model so it's accessible inside the callback like this:

getStatus : function() {
    var model = this;
    $.getJSON(this.url(), function(data) {
        model.set({status : data.status});
    }); 
}

Upvotes: 1

Related Questions