What's wrong with the following code?
(function(){
window.App = {
Models: {},
Collections: {},
Views: {}
};
window.template = function(id) {
return _.template($('#' + id).html());
};
App.Models.Task = Backbone.Model.extend({
defaults:{
title: '',
priority: 0
},
validate: function(attrs, options){
if (attrs.priority < 0){
return 'Priority cannot be negative.';
}
}
});
var task = new App.Models.Task ({ title: 'Sample Task', priority: 5 });
task.on('invalid', function(model, error) { console.log(error); })
task.save({ priority: -9 }); // Should not pass validation
console.log(task.validationError); // Prints a validation error
console.log(task.toJSON()); // Model is updated with -9
console.log(task.isValid()); // false
})();
Output:
Priority cannot be negative. app.js:27
Priority cannot be negative. app.js:30
Object {title: "Sample Task", priority: -9} app.js:32
Priority cannot be negative. app.js:27
false
I am currently watching a video tutorial and it's based on old version of backbone.js where validation was by default enforced on the set
method. But in the current version validation is by default enforced on the save
method.
But even though it's not a valid value and the validation doesn't pass why is it still setting the value to -9. Isn't it supposed to not set the value when the validation doesn't pass?
With the new version, when saving new data, you need to pass the validation option:
task.save({ priority: -9 }, {validation: true});