Reputation: 14770
I need to catch a "beforeChange
" event, to prepare some stuff before a model's field changes. Does BackboneJS have something like this, or how could I accomplish something similar?
Upvotes: 2
Views: 191
Reputation: 2796
There's no such thing as a "beforeChange
" event—but there are a few ways I know of to accomplish a similar kind of thing.
model.set
The easiest thing to do is override model.set
Example: http://jsfiddle.net/dkho4p2r/
var Foo = Backbone.Model.extend({
set: function (attributes, options) {
// do stuff here
Backbone.Model.prototype.set.apply(this, arguments);
}
});
model.validate
You also have access to model.validate
, which—if you pass the validate: true
option when calling model.set
—is called before the model is actually changed.
Example: http://jsfiddle.net/dkho4p2r/1/
This probably isn't the best place to put arbitrary code, but it fits the requirement of occurring before the model's change
event.
model.set
This may be the too-obvious answer you were looking to avoid, but you can always just "prepare some stuff" before calling set()
on your model. Example: http://jsfiddle.net/dkho4p2r/2/
data = prepareSomeStuff(data);
model.set(data);
Upvotes: 2