It is easy to bind to the 'error' event of an existing model, but what is the best way to determine if a new model is valid?
Car = Backbone.Model.extend({
validate: function(attributes) {
if(attributes.weight == null || attributes.weight <=0) {
return 'Weight must be a non-negative integer';
}
return '';
}
});
Cars = Backbone.Collection.extend({
model: Car
});
var cars = new Cars();
cars.add({'weight': -5}); //Invalid model. How do I capture the error from the validate function?
I haven't tested this, but I'm pretty sure that all events on all models in a collection will be passed to and triggered by the collection as well. So you should be able to listen to the
error
event on the collection:Edit: Nope, this works for setting properties on existing models, but not on model creation. Ugh - it looks like there's no way to listen for this without overriding some part of the Backbone code. Models don't perform validation when they're initialized:
And while
collection.add()
does perform validation, it fails silently.If you use
collection.create()
instead ofcollection.add()
, you can check, since.create()
will returnfalse
on failure. But this will try to create the model on the server, which might not be what you want.So, I think the only way to do this is to override
collection._prepareModel
and trigger a custom event, like this:Example here: http://jsfiddle.net/nrabinowitz/f44qk/1/
Validation logic can be triggered explicitly by calling the
validate
method of your model. This will not, however, cause anerror
event to be triggered. You can trigger an error event manually for a model by calling thetrigger
method.One way to achieve your desired behavior is to manually trigger the event in your initialization method:
i encountered problem like it
my solution