Hi I am new to backbonejs,
I have encountered a problem while i was trying an example of http://addyosmani.github.com/backbone-fundamentals/#validation
I have created an 2 object of model, myTodo and myTodo1,
if I call set function like this, it return completed:false due to validation error
var myTodo = new Todo();
myTodo.set('completed', true, {validate: true});
console.log("completed: "+myTodo.get('completed'));
/*
The above code returns following log:
This model has been initialized.
Remember to set a title for your todo.
completed: false
*/
buy why validation is not executing on execution of below code
var myTodo1 = new Todo();
myTodo1.set('completed',true);
console.log("completed: "+myTodo1.get('completed'));
myTodo1.set({validate:true})
console.log("completed: "+myTodo1.get('completed'));
/*
The above code returns following log:
This model has been initialized. underscore-test2.js:11
completed: true underscore-test2.js:28
completed: true
*/
although both set of code doing the same job, but in first case validation executes but not in second case
Why?????
below is the full example code.
var Todo = Backbone.Model.extend({
defaults: {
completed: false,
},
validate: function(attribs){
if(attribs.title === undefined){
return "Remember to set a title for your todo.";
}
},
initialize: function(){
console.log('This model has been initialized.');
this.on("invalid", function(model, error){
console.log(error);
});
this.on('change:title', function(){
console.log('- Values for title have changed.');
});
}
});
**var myTodo = new Todo();
myTodo.set('completed', true, {validate: true});
console.log("completed: "+myTodo.get('completed'));**
**var myTodo1 = new Todo();
myTodo1.set('completed',true);
console.log("completed: "+myTodo1.get('completed'));
myTodo1.set({validate:true})
console.log("completed: "+myTodo1.get('completed'));**
myTodo1.set({validate:true})is setting an attribute calledvalidateto true. TrymyTodo1.set({validate:'hello!'}); console.log(myTodo1.get('validate'));in your code, and you will see this has nothing to do with running your validate function. - Paul Hoenecke