如何在新的主干中捕获验证错误?实例化期间的模型

How can I capture validation errors in a new Backbone.Model during instantiation?

本文关键字:错误 验证 实例化 模型      更新时间:2023-09-26

很容易绑定到现有模型的'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
});