I’m using Backbone and Marionette, I’m retrieving my models from a backend.
The models belong to a collection.
The problems are:
1) The validate method is never called unless explicitly from within the initialize. Why?
2) When I explicitly call the validate method, it correctly returns for an invalid model I created for testing. But I am not able to catch the “invalid” event. What am I doing wrong?
Here’s the model:
var Job = Backbone.Model.extend({
validate: function(attrs){
if (! attrs.title ) {
return "A job should have a title";
}
},
initialize: function(){
this.validate(this.attributes); //manual call to validate
this.on("invalid", function(model, error){ //never executed even when the validate model returns the error string
console.log(error);
});
}
});
And here the Collection:
var JobList = Backbone.Collection.extend({
model: Job,
url: '/api/1.0/jobs/',
parse: function(response) {
return response.results;
}
});
The validation logic was changed in Backbone
0.9.10. Quoting from the change log, validation now works as follows:So if you want the model to be validated upon initialization or
set, you need to pass the optionvalidate:trueto the constructor / method.The reason you are not receiving the
invalidevent when you manually call yourmodel.validatemethod is that Backbone is not performing any of the validation when you do. You call a method you defined on the model, and Backbone doesn’t know anything about it.Model validation in Backbone is convention based in the sense that Backbone doesn’t define a method called
validateon the model – you do yourself. However, if you have defined such a method, Backbone will call it for you when validation occurs (onsave, or in constructor/setter withvalidate:true, and theinvalidevent will be triggered.