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

aw *_*rud 5 javascript backbone.js

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

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?
Run Code Online (Sandbox Code Playgroud)

Ken*_*ing 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 '';
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这正是我所需要的.有时,Backbone文档并不能很好地充实细节. (2认同)