Backbone:更改事件后更新模型

Bar*_*obs 3 javascript backbone.js

假设具有以下属性的Backbone模型: - 小计 - 折扣 - 总计

每当对折扣进行更改时,总需要更新,我希望模型能够解决这个问题.

我已经尝试将更新方法(在模型中定义)绑定到模型的更改事件(在模型的初始化方法中),以便对于每个更改事件,模型将更新总属性,但这似乎不起作用.

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

    update      : function() {
        // UPDATE LOGIC
    }
});
Run Code Online (Sandbox Code Playgroud)

当模型触发更改事件时,让模型触发(自己的)方法的最佳方法是什么?

nik*_*shr 9

你使用set模型的方法吗?这段代码在discount更改时调用update :

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});
Run Code Online (Sandbox Code Playgroud)