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

后端 未结 4 1969
故里飘歌
故里飘歌 2021-02-10 06:20

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({
  va         


        
4条回答
  •  暖寄归人
    2021-02-10 06:52

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

提交回复
热议问题