sty*_*ler 3 javascript jquery backbone.js
开始学习Backbone,尝试在我的Person Model中进行一些简单的验证,但是当我设置一个新的年龄时,似乎没有运行validate方法.任何人都可以解释我可能在哪里出错吗?在我做对了之前,不要继续我的学习.
JS
var Person = Backbone.Model.extend({
defaults: {
name: 'John Doe',
age: 30,
occupation: 'working'
},
validate: function(attrs) {
console.log(attrs);
if ( attrs.age < 0 ) {
return 'Age must be positive, stupid';
}
if ( ! attrs.name ) {
return 'Every person must have a name, you fool.';
}
},
work: function() {
return this.get('name') + ' is working.';
}
});
Run Code Online (Sandbox Code Playgroud)
目前我只是在控制台中获取并设置值,因此:
var person = new Person({
name: 'Lady Madonna',
age: 23
});
person.on('error', function(model, error){
console.log(error);
});
Run Code Online (Sandbox Code Playgroud)
当我将age设置为负值时,validate方法不会生效:
person.set('age', -55);
Run Code Online (Sandbox Code Playgroud)
nik*_*shr 10
Backbone 0.9.10中的模型验证已更改:
模型验证现在仅在Model#save中默认强制执行,并且在构造或Model#set中不再默认强制执行,除非
{validate:true}
传递选项.
并注意到
模型验证现在触发无效事件而不是错误.
所以你的代码应该写成
var person = new Person({
name: 'Lady Madonna',
age: 23
});
person.on('invalid', function(model, error){
console.log(error);
});
person.set('age', -55, {validate : true});
Run Code Online (Sandbox Code Playgroud)
还有一个小提琴http://jsfiddle.net/nikoshr/aUxdS/