javascript Backbone:更改事件后更新模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8434099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:26:19  来源:igfitidea点击:

Backbone: Update model after change event

javascriptbackbone.js

提问by Bart Jacobs

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

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

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.

我尝试将更新方法(在模型中定义)绑定到模型的更改事件(在模型的 initialize 方法中),以便在每个更改事件中,模型都会更新 total 属性,但这似乎不起作用。

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?

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

回答by nikoshr

Do you use the setmethod of the model? This bit of code calls update when discountis changed:

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

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