Permalink
Browse files

feat(form): convenience class Form rewrite

  • Loading branch information...
bas080
bas080 committed Jun 13, 2016
1 parent 33c9e1b commit 4aa75417887d908b11f48f0e1ed66857ce8b1f60
Showing with 30 additions and 18 deletions.
  1. +30 −18 src/form.js
@@ -4,32 +4,41 @@ import {Validator, ValidationEngine} from 'aurelia-validatejs';
* Some functionalities are desired in a view model of a form. Responsibilites
* include validation and submit.
*
* This class is optional and serves as a convenience class
* This class is optional and serves as a convenience class.
*
* - creates a messages property for storing error strings
* - allows you to set the model which automaticall
* - automatically triggers validation
* - convenient methods that can be overwritten to perform action on submit and
* change
*/
export class Form {

messages = {}

_model

constructor() {}

set model(newModel) {
this._model = newModel;
this.validator = new Validator(newModel);
this.reporter = ValidationEngine.getValidationReporter(newModel);
this.observer = this.reporter.subscribe(validationErrors => {
this.messages = validationErrors.reduce( (acc, error) => {
acc[error.propertyName] = error.message;
return acc;
}, {});
/***
* Used to get access to onSubmit and model changes could also wrap the
* change and submit methods instead
*/
onChange() {}
onSubmit() {}

constructor() {
this.__defineSetter__('model', (model) => {
this.onChange(model, this.model);
this.__defineGetter__('model', () => model);
this.observer && this.observer.dispose();
this.validator = new Validator(model);
this.reporter = ValidationEngine.getValidationReporter(model);
this.observer = this.reporter.subscribe(validationErrors => {
this.messages = validationErrors.reduce( (errors, error) => {
errors[error.propertyName] = error.message;
return errors;
}, {});
});
});
}

get model() {
return this._model;
}

validate() {
this.validator.validate();
}
@@ -39,9 +48,12 @@ export class Form {
}

submit() {
this.onSubmit(this.model);
this.validate();
}

change() {
this.onChange(this.model);
this.validate();
}

0 comments on commit 4aa7541

Please sign in to comment.