Trunk - model check was not called and there was no invalid event

I use Backbone and Marionette, I extract my models from the backend.
Models belong to the collection. Problems:

1) The validate method is never called unless explicitly from initialization. Why?
2) When I explicitly call the validate method, it correctly returns an invalid model created for testing. But I can’t catch the “invalid” event. What am I doing wrong?

Here is 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 is the collection:

 var JobList = Backbone.Collection.extend({ model: Job, url: '/api/1.0/jobs/', parse: function(response) { return response.results; } }); 
+4
source share
1 answer

Validation logic has been changed in Backbone 0.9.10 . Quoting from the change log, the check now works as follows:

Model validation is now applied only by default in saving Model # and is no longer applied by default when building or in the Model # set if the {validate: true} option is not passed.

So, if you want the model to be checked during initialization or set , you need to pass the validate:true option to the constructor / method.

The reason you don't accept the invalid event when manually calling the model.validate method is because Backbone does not perform any checks when you do this. You call the method that you defined on the model, and Backbone knows nothing about it.

Checking the model in the baseline is based on the convention that Backbone does not define a method called validate on the model — you do it yourself. However, if you define such a method, Backbone will call it for you when checking (in save or in the constructor / setter with validate:true , and the invalid event will occur.

+5
source

All Articles