【问题标题】:Backbone: Update model after change event主干:更改事件后更新模型
【发布时间】:2012-01-16 01:45:13
【问题描述】:

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

每当对折扣进行更改时,总需要更新,我希望模型能够处理这一点。

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

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

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

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

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    你使用模型的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});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 2012-12-22
      • 2014-09-18
      相关资源
      最近更新 更多