次のコードの何が問題になっていますか?
(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
})();
出力:
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
私は現在、ビデオチュートリアルを見ています。これは、デフォルトでset
メソッドに検証が適用されていた古いバージョンの backbone.js に基づいています。しかし、現在のバージョンでは、検証はデフォルトでsave
メソッドに適用されます。
しかし、それは有効な値ではなく、検証に合格しないにもかかわらず、値を -9 に設定しているのはなぜですか。バリデーションが通らない場合は値を設定しないはずではないですか?