gpt4 book ai didi

javascript - 如何在实例化期间捕获新 Backbone.Model 中的验证错误?

转载 作者:数据小太阳 更新时间:2023-10-29 05:47:07 26 4
gpt4 key购买 nike

绑定(bind)到现有模型的“错误”事件很容易,但是确定新模型是否有效的最佳方法是什么?

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

关于javascript - 如何在实例化期间捕获新 Backbone.Model 中的验证错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7923074/

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