When either of two attributes (“a” or “b”) change in my Backbone model, I’d like to calculate a third attribute “c”:
initialize: function() {
this.bind("change:a", this.calculateC);
this.bind("change:b", this.calculateC);
},
calculateC: function() {
this.attributes.c = ...
}
What is a good way of preventing c from being calculated twice if both a and b are set on the model simultaneously?
The attributes will not be set simultaneously, they will be set one at time so you need to see both events. The relevant code looks like this:
You can see that one of the attributes is set, then its change event is triggered, then the process is repeated for the next attribute. If you only want one event, then you should bind only to the whole model’s change event.
For completeness I should mention that the interface documentation for
Model#setdoesn’t specify any particular behavior as to when the individual change events will be triggered, it only says that they will be triggered.