gpt4 book ai didi

javascript - Backbone 模型中的验证方法未被调用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:57:19 25 4
gpt4 key购买 nike

开始学习 Backbone,尝试在我的 Person 模型中做一些简单的验证,但是当我设置新的年龄时,验证方法似乎没有运行。谁能解释我在这方面可能哪里出错了?在我做对之前不想继续我的学习。

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.';
}

});

目前我只是在控制台中获取和设置值,所以:

var person = new Person({
name: 'Lady Madonna',
age: 23
});

person.on('error', function(model, error){
console.log(error);
});

当我将年龄设置为负值时,验证方法不生效:

person.set('age', -55);

最佳答案

模型验证 changed in Backbone 0.9.10 :

Model validation is now only enforced by default in Model#save and no longer enforced by default upon construction or in Model#set, unless the {validate:true} option is passed.

并注意

Model validation now fires invalid event instead of error.

所以你的代码应该写成

var person = new Person({
name: 'Lady Madonna',
age: 23
});

person.on('invalid', function(model, error){
console.log(error);
});

person.set('age', -55, {validate : true});

还有一把 fiddle http://jsfiddle.net/nikoshr/aUxdS/

关于javascript - Backbone 模型中的验证方法未被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15614826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com