每当我将age属性设置为负值时,它都不会返回false。 我也尝试在控制台中执行此代码,但仍未发生任何事情
<script>
var Human = Backbone.Model.extend({
// If you return a string from the validate function,
// Backbone will throw an error
defaults: {
name: 'Guest user',
age: 23,
occupation: 'worker'
},
validate: function( attributes ){
if( attributes.age < 0){
return "Age must me positive";
}
if( !attributes.name ){
return 'Every person must have a name';
}
},
work: function(){
return this.get('name') + ' is working';
}
});
var human = new Human;
human.set("age", -10);
human.on('error', function(model, error){
console.log(error);
});
</script>
答案 0 :(得分:2)
您的代码存在一些问题:
invalid
,error
适用于ajax请求。{ validate: true }
作为选项。即:
human.on('invalid', function(model, error) {
console.log(error);
});
human.set("age", -10, { validate: true });