我怎样才能实例化过程中捕捉新的Backbone.Model验证错误? [英] How can I capture validation errors in a new Backbone.Model during instantiation?

查看:153
本文介绍了我怎样才能实例化过程中捕捉新的Backbone.Model验证错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是很容易结合到现有模型的错误事件,但什么是确定是否有新的模型是有效的最佳方式?

 汽车= Backbone.Model.extend({
  验证:功能(属性){
    如果(attributes.weight == NULL || attributes.weight< = 0){
      返回重量必须是一个非负整数';
    }
    返回'';
  }
});汽车= Backbone.Collection.extend({
  型号:汽车
});VAR车=新车();
cars.add({'体重':-5}); //无效的模型。我如何捕获从验证函数的错误?


解决方案

验证逻辑可以显式调用验证模型的方法所触发。这不,但是,导致错误事件被触发。您可以通过调用触发手动触发错误事件的模型方法。

要实现你期望的行为的一种方法是在你的初始化方法来手动触发事件:

 汽车= Backbone.Model.extend({
  初始化:功能(){
    Backbone.Model.prototype.initialize.apply(这一点,参数);
    VAR误差= this.validate(this.attributes);
    如果(错误){
      this.trigger('错误',这一点,错误);
    }
  },
  验证:功能(属性){
    如果(attributes.weight == NULL || attributes.weight< = 0){
      返回重量必须是一个非负整数';
    }
    返回'';
  }
});

It is easy to bind to the 'error' event of an existing model, but what is the best way to determine if a new model is valid?

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?

解决方案

Validation logic can be triggered explicitly by calling the validate method of your model. This will not, however, cause an error event to be triggered. You can trigger an error event manually for a model by calling the trigger method.

One way to achieve your desired behavior is to manually trigger the event in your initialization method:

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

这篇关于我怎样才能实例化过程中捕捉新的Backbone.Model验证错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆