javascriptbackbone.jsbackbone-relational

How to remove validationError from the model in store?


I made an error while updating the model, and the model now has validation errors in the validationError model property.

But even I fetch the collection again and got new data for the model, the model's validationError is not gone in store.

So in list view, the collection length shows 0. Even if it has one, I confirmed it in store.

How can I remove the validationError on the model when I fetch the collection?


Solution

  • Dealing with invalid data

    If the data was stored within the database with an invalid state, you can either:

    A simple parse function could look like:

    var MyModel = Backbone.Model.extend({
      /**
       * Called with the raw response data
       */
      parse: function(data, options) {
        // fix the problem within the data object.
        if (_.has(data, 'myAttribute')) {
          data.myAttribute = /* correction here */
        }
        // return the fixed data object
        return data;
      }
    });
    

    Why the collection length is zero?

    It's because the collection sends the received data (locally as a param or following a fetch) to its private _prepareModel method which ensure that the data is a valid Backbone Model.

    _prepareModel: function(attrs, options) {
      if (this._isModel(attrs)) {
        if (!attrs.collection) attrs.collection = this;
        return attrs;
      }
      options = options ? _.clone(options) : {};
      options.collection = this;
      var model = new this.model(attrs, options);
      if (!model.validationError) return model;
      this.trigger('invalid', this, model.validationError, options);
      return false;
    },
    

    It returns the model only if validationError is falsy (null by default and thruty whenever a validation rule returned an error message string or array).

    if (!model.validationError) return model;
    

    Otherwise, it returns false and doesn't add the model to the collection.