Skip to content

Instantly share code, notes, and snippets.

@rogercbe
Last active May 13, 2018 21:00
Show Gist options
  • Select an option

  • Save rogercbe/f7e1417c31007c9241f52c44e20f53bb to your computer and use it in GitHub Desktop.

Select an option

Save rogercbe/f7e1417c31007c9241f52c44e20f53bb to your computer and use it in GitHub Desktop.
Form Object
class Errors {
constructor() {
this.errors = {};
}
get(field) {
if (this.errors[field]) {
return this.errors[field][0];
}
}
has(field) {
return this.errors[field];
}
any() {
return Object.keys(this.errors).lenght > 0;
}
clear(field) {
delete this.errors[field];
}
fill(errors) {
this.errors = errors;
}
}
export { Errors as default }
import Errors from './Errors.js';
class Form {
constructor(fields) {
this.fields = fields;
this.errors = new Errors();
this.message = '';
this.processing = false;
}
submit(method, uri) {
this.processing = true;
return new Promise((resolve, reject) => {
axios[method](uri, this.fields)
.then(response => {
this.onSuccess(response.data);
resolve(response.data);
})
.catch(error => {
this.onFail(error.response.data);
reject(error.response.data)
});
});
}
onSuccess(data) {
this.reset();
this.processing = false;
this.message = data.message;
}
onFail(data) {
this.processing = false;
this.errors.fill(data.errors);
}
reset() {
for (let field in this.fields) {
this.fields[field] = '';
}
}
}
export { Form as default }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment