Search code examples
validationbackbone.js

set validate to default to true with Backbone "set"


In the code I am working with using Backbone 1.0.0, the validate function of my model is only called when I go:

myThing.set( "title", "My title string", { validate : true } );

Is there a way in the initialize function of my model to set the default to true so that this:

myThing.set( "title", "My title string" );

Would cause the validate function to be called?


Solution

  • There are no way to override the default behaviors of the methods, but you can still override the set method directly, something like:

    var set = Backbone.Model.prototype.set;
    Backbone.Model.prototype.set = function(key, val, options) {
      return set.call(this, key, val, _.extend({validate: true}, options));
    }
    

    Keep in mind that the set method has to deal with 2 different cases (as it allows to pass an object as argument as well). So this example won't work all the time. You can refer to the actual Backbone code to see an example of how it's done.