如何在新的主干中捕获验证错误?实例化期间的模型
How can I capture validation errors in a new Backbone.Model during instantiation?
很容易绑定到现有模型的'error'事件,但是确定新模型是否有效的最佳方法是什么?
Car = Backbone.Model.extend({
validate: function(attributes) {
if(attributes.weight == null || attributes.weight <=0) {
return 'Weight must be a non-negative integer';
}
return '';
}
});
Cars = Backbone.Collection.extend({
model: Car
});
var cars = new Cars();
cars.add({'weight': -5}); //Invalid model. How do I capture the error from the validate function?
可以通过调用模型的validate
方法显式触发验证逻辑。但是,这不会导致触发error
事件。您可以通过调用trigger
方法手动触发模型的错误事件。
Car = Backbone.Model.extend({
initialize: function () {
Backbone.Model.prototype.initialize.apply(this, arguments);
var error = this.validate(this.attributes);
if (error) {
this.trigger('error', this, error);
}
},
validate: function(attributes) {
if(attributes.weight == null || attributes.weight <=0) {
return 'Weight must be a non-negative integer';
}
return '';
}
});
我还没有测试过,但我很确定集合中所有模型上的所有事件都将传递给集合并由集合触发。因此,您应该能够在集合上侦听error
事件:
var cars = new Cars();
cars.bind('error', function() {
console.log('Model not valid!')
})
cars.add({'weight': -5});
Edit:不,这适用于在现有模型上设置属性,但不适用于模型创建。啊——看起来没有办法在不重写骨干代码的某些部分的情况下监听这个。模型初始化时不执行验证:
var car = new Car({weight: -5});
console.log(car.get('weight')); // no error, logs -5
当collection.add()
执行验证时,它会静默失败。
如果您使用collection.create()
而不是collection.add()
,您可以检查,因为.create()
将在失败时返回false
。但是这将尝试在服务器上创建模型,这可能不是您想要的。
所以,我认为这样做的唯一方法是重写collection._prepareModel
并触发自定义事件,像这样:
Cars = Backbone.Collection.extend({
model: Car,
_prepareModel: function(model, options) {
model = Backbone.Collection.prototype._prepareModel.call(this, model, options);
if (!model) this.trigger('error:validation');
return model;
}
});
var cars = new Cars();
cars.bind('error:validation', function() {
console.log('Model not valid!')
});
cars.add({'weight': -5}); // logs: 'Model not valid!'
示例:http://jsfiddle.net/nrabinowitz/f44qk/1/
我遇到了这样的问题
我的解决方案...
var handler = function(model, error, context) {}
try {
cars.add({}, { error: handler })
} catch (e) { }
...
this.collection.fetch({
validate: true
});
相关文章:
- 为什么jasmine期望不验证是否抛出了错误
- jQuery在输入下验证post错误消息
- JavaScript表单验证-“;“错误”;不按需要工作
- 当与Dojo验证一起使用时,Chrome 41密码保存会做出错误的选择
- jquery表单验证复选框错误显示
- 页面上的2个表单带有JS验证-其中一个抛出电子邮件验证错误
- 在页面对象文件中验证sendKeys结果会导致未定义的错误(Protractor)
- 表单值未在单击按钮时发布,显示验证错误
- 表单已发送,但验证有错误
- TinyMCE验证给出错误:无法调用方法'getContent'的未定义
- Javascript表单验证-jsFiddle错误
- 无法使用JavaScript打印带有for循环的验证错误
- 为什么我的 JavaScript 会导致 HTML 验证错误
- 错误验证在AngularJS中不起作用
- 在线错误验证
- 接收package.json的解析错误.验证为有效的json
- 错误验证 W3C HTML5 img noscript facebook.com.
- 使用jquery输入文件类型错误验证不工作
- 带有警报的表单错误验证
- Angularjs用ng-href对dropdown/select redirect进行错误验证