3
votes

Assume a Backbone model with the following attributes: - subtotal - discount - total

Whenever a change is made to discount, the total needs to be updated and I'd like the model to care of this.

I have tried binding an update method (defined in the model) to the model's change event (in the model's initialize method) so that with each change event, the model would update the total attribute, but this does not seem to work.

var Cost = Backbone.Model.extend({
    initialize  : function() {
        this.bind('change', this.update);
    },

    update      : function() {
        // UPDATE LOGIC
    }
});

What is the best approach to have the model fire a method (of its own) when it triggers a change event?

1

1 Answers

9
votes

Do you use the set method of the model? This bit of code calls update when discount is changed:

var Cost = Backbone.Model.extend({
    defaults: {
        subtotal: 0,
        discount: 0,
        total: 0
    },
    initialize: function () {
        _.bindAll(this, "update");
        this.on('change:discount', this.update);
        // or, for all attributes
        // this.on('change', this.update);
    },

    update: function () {
        console.log("update : "+this.get("discount"))
    }
});

var c = new Cost();
c.set({discount: 10});