以下代碼有什麼問題?Backbone.js模型驗證不起作用
(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。當驗證不通過時它不應該設置值嗎?
你究竟在期待什麼?你設置了一個負面的優先級,所以你不通過驗證,所以..? (順便說一句,不是輸出中的第4行?我覺得它不應該在這裏) – Loamhoof
是不是不應該將值設置爲-9,因爲驗證不通過? – Zuhaib