简体   繁体   中英

Dependent attributes in Backbone.js model

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM