在Backbone.js的模型依赖的属性 [英] Dependent attributes in Backbone.js model

查看:187
本文介绍了在Backbone.js的模型依赖的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果任何两个值 - a或b - 在我的模型的变化,两者的听音意见需要计算第三个值c。

If either of two values - a or b - change in my model, two of the listening views need to calculate a third value c.

//Pseudo 
mainModel 
  a : 2000 
  b : 3000

view1 
helper.calculateC(this.model.get(a), this.model.get(b)) 

view2 
helper.calculateC(this.model.get(a), this.model.get(b)) 

我宁愿把有关的属性c。在模型(如
计算是相当复杂和C可能稍后被允许为
由用户覆盖。)什么是好的做法呢?我是否应该延长
模型,做一个子模型还是什么?

I'd rather put the dependent attribute c in the model (as the calculation is rather complex and "c" might later on be allowed to be overridden by the user.) What is good practice? Should I extend the model, make a submodel or what?

谢谢!

推荐答案

您可以添加在模型在初始化调用自己的变化的事件。

You can add a binding on the model to its own change event on the initialize call.

initialize: function() {
  this.bind("change", this.calculateC);
},

calculateC: function() {
  this.c = //fill in the blanks
}    

更具体地说,你只能在你需要的属性绑定。

More specifically, you can bind only on the attributes you need.

  this.bind("change:a", this.calculateC);
  this.bind("change:b", this.calculateC);

这篇关于在Backbone.js的模型依赖的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆