I think what I want to do is pretty simple I just don't know how to do it. I would like to fire my own event when one of my models attributes changes for the purpose of passing some data to the event handler (whether the change was an increase or decrease in value).
Basically I want my handler to do this in the view
handler: function(increased) {
if(increased) {
alert("the value increased")
}
else {
alert("the value decreased")
}
}
// ...
this.model.on("change:attr", this.handler, this);
Here you go: You basically listen for
change:myvar
. When a change occurs you use your model'sprevious()
to get the old value. Depending on whether it increased or decreased you fire the appropriate event. You can listen to these events as shown in theinitialize()
.Running the above will print "Increased", "Increased", "Decreased" to your console.
Just look at
previousAttributes()
You can then compare:
If you use that in your
change
event handler you're all set. No need for a custom trigger or a ton of code.EDIT
This is from my Backbone.Validators project and how I obtain the list of all attributes which have changed during the validation step:
This requires Underscore 1.3.1 because it's using
_.has
. If you can't upgrade that's an easy thing to replace though. In your case you'd passingthis.previousAttributes()
andthis.attributes
What if you fire your own custom event after listening to the change event?