Dependent attributes in Backbone.js model

2019-08-22 02:18发布

问题:

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

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?

Thanks!

回答1:

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