如何在实例化新的Backbone.Model时捕获验证错误?

5

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

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?
4个回答

12

您可以通过调用模型的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 '';
  }
});

2
谢谢,这正是我所需要的。有时候 Backbone 的文档并不是很详细。 - PetrolMan

1

我遇到了类似的问题

我的解决方案

...

var handler = function(model, error, context) {}

try {
  cars.add({}, { error: handler })
} catch (e) { }        

...

1

我没有测试过,但我非常确定集合中所有模型的所有事件也将被传递和触发。因此,您应该能够在集合上侦听error事件:

var cars = new Cars();
cars.bind('error', function() {
    console.log('Model not valid!')
})
cars.add({'weight': -5});

编辑: 不行,这个方法可以用于设置现有模型的属性,但不能在创建模型时使用。唉 - 看起来没有办法在不覆盖Backbone代码的情况下监听此事件。当模型被初始化时,它们不执行验证:

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/


0
this.collection.fetch({
    validate: true
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接