Backbone: Update model after change event

10,541

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});
Share:
10,541
Bart Jacobs
Author by

Bart Jacobs

Bart Jacobs runs Code Foundry, a mobile and web development company based in Belgium and writes about iOS and Swift development on his blog. Bart is also the mobile editor of Envato Tuts+.

Updated on June 04, 2022

Comments

  • Bart Jacobs
    Bart Jacobs almost 2 years

    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?