骨干验证功能没有得到所谓的 [英] Backbone validate function not getting called
问题描述
我的验证功能是没有得到所谓的下code: -
My validate function is not getting called in the code below:-
var Vehicle = Backbone.Model.extend({
color: 'green',
validate: function (attrs) {
var validColors = ['white', 'red', 'blue', 'yellow'];
var colorIsValid = function (attrs) {
if (!attrs.color) return true;
return _.contains(validColors, attrs.color);
}
if(!colorIsValid(attrs)) {
return "color must be one of: " +validColors.join(",");
}
}
});
var car = new Vehicle();
car.on('error', function (model, error) {
console.log(error);
});
console.log(car.get('color'));
car.set('color', 'muave');
请参阅小提琴
http://jsfiddle.net/vineet85/Fa8jr/5/
谁能告诉我,为什么验证功能是没有得到所谓的?
Can someone tell me why the validate function is not getting called?
推荐答案
在Backbone.js的验证
将自动在称为保存
而不是在设置
。
In Backbone.js validate
is called automatically on save
but not on set
.
如果您想验证到设定值时运行,你需要使用验证
选项。例如。
If you want validations to run when setting a value you will need to use the validate
option. e.g.
car.set('color', 'muave', {validate: true});
请参阅 http://backbonejs.org/#Model-validate
当错误发生时,通常在服务器上,试图保存对象时,会触发错误
事件。请参见 http://backbonejs.org/#Events-catalog
The error
event is triggered when an error occurs, typically on the server, when trying to save the object. See http://backbonejs.org/#Events-catalog
如果你想赶上验证失败尝试处理无效
事件:
If you want to catch validation failures try handling the invalid
event:
car.on('invalid', function (model, error) {
console.log(error);
});
这篇关于骨干验证功能没有得到所谓的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!