lcoq / ember-validations

Ember-Validations - An Ember.js library for handling object validations
MIT License
122 stars 25 forks source link

Monitoring errors changes #38

Open panta82 opened 10 years ago

panta82 commented 10 years ago

Hi, I want to create a tooltips property that would contain processed error data from corresponding validators (key to key mapping). For that, I need to listen to any change in validation errors and update my tooltips hash.

The first thing I tried was attaching directly to the .errors property on the model. However, I don't get notifications when its error arrays change and there is no equivalent to @each for properties (barring some hacks I found online).

Then I tried attaching to some variation of validators.@each construct. Unfortunately, I would need validators.@each.errors.@each and that's a bit further than Ember allows.

Do you have any idea what I could attach or listen to? Some kind of global allErrors property would be ideal for this, but I would take anything at this point.

panta82 commented 10 years ago

Actually, I just went ahead and implemented allErrors property.

validator.addObserver('errors.[]', this, function (sender, key, value, context, rev) {
    var errors = Ember.makeArray();
    var allErrors = Ember.makeArray();
    this.validators.forEach(function (validator) {
        if (validator.property === sender.property) {
            errors = errors.concat(validator.errors);
        }
        allErrors = allErrors.concat(validator.errors.map(function (message) {
            return {
                property: validator.property,
                message: message
            };
        }));
    }, this);
    this.set('errors.' + sender.property, errors);
    this.set('allErrors', allErrors);
});

I'm not sure how useful this would be in general (could be helpful for some kind of error summary widget), but it solved my problem for now.