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?
Backbone will always call the
validatemethod when yousetorsavean attribute with the exception of when you pass in a hash to the constructor or when the model instantiates with thedefaulthash.e.g.
Will NOT call the
validatemethod since the constructor MUST return a new instance of the model.However,
Will.
Your
validatemethod will never print out anything — thereturnon 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
defaultshash 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!)