admin管理员组

文章数量:1346287

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?

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?

Share Improve this question asked Dec 8, 2011 at 16:19 Bart JacobsBart Jacobs 9,0827 gold badges49 silver badges89 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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

本文标签: javascriptBackbone Update model after change eventStack Overflow