Is Validation on Models in Backbone only done when

2019-08-10 08:04发布

问题:

I have created an object:

var Person = Backbone.Model.extend({
  defaults: {
    'name': '',
    'age': 0
  },
  initialize: function() {
    this.on('error', function(model, error){
      console.log(error);
    });
  },
  validate: function(attributes){
    if (attributes.name == '') {
      return "How do we call him!?";
    }
  },
  changeName: function(name) {
    this.set({'name':name});
  },
  getOlder: function() {
    this.set({'age': this.get('age') +1});
  }   
});

I create an instance of Person and put in a blank on the name and I never received an error. But when I set a blank name on an already created instance, it fired the validation.

var teejay = new Person;
teejay.changeName('');
=> How do we call him!?
teejay.get('name');
=> ""

From what I am seeing from the Backbone source code, I see

this.set(attributes, {silent: true});

Is it right to assume that validation is only done whenever attributes are changed or set?

回答1:

Backbone will always call the validate method when you set or save an attribute with the exception of when you pass in a hash to the constructor or when the model instantiates with the default hash.

e.g.

var myperson = new Person({name: ''});

Will NOT call the validate method since the constructor MUST return a new instance of the model.

However,

var myperson = new Person();
myperson.set('name', '');

Will.

Your validate method will never print out anything -- the return on validate is used to test whether or not it worked. If you return anything "truthy" validation will fail, but that's it. It's up to you to trigger the 'error' message or whatever else you want.

What you're seeing is exactly as should be expected.

TL;DR: Your defaults hash will not ever be validated since it has to return a valid model.

(Also, allow me to shill for my Backbone.Validator project now -- don't write your own!)