How can I capture validation errors in a new Backbone.Model structure during instance creation?

It is easy to bind an existing model to the error event, 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?
+5
source share
4 answers

Validation logic can be invoked explicitly by calling validateyour model's method . However, this will not trigger the event error. You can trigger the error event manually for the model by calling the method trigger.

One way to achieve the desired behavior is to manually trigger an event in the 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 '';
  }
});
+12
source

, , . , error :

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

: , , . - , , . :

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/

+1

I encountered such a problem

my decision

...

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

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

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

All Articles