Skip to content

Instantly share code, notes, and snippets.

@Ifmr24
Created May 17, 2020 04:23
Show Gist options
  • Save Ifmr24/86003c256bd4d5328af1805635507ac8 to your computer and use it in GitHub Desktop.
Save Ifmr24/86003c256bd4d5328af1805635507ac8 to your computer and use it in GitHub Desktop.
JS Patron Observador
class FormState {
constructor(){
this.fields = {};
this.subscribers = [];
}
subscribe(callback) {
this.subscribers.push(callback)
}
notify() {
this.subscribers.map((sub) => sub(this.fields))
}
updateField(params) {
const {name, value} = params;
this.fields[name] = value;
this.notify()
}
}
const formState = new FormState()
export default formState
import formState from './formstate.js';
const formValuesWrapper = document.querySelector('#formValues');
formState.subscribe((fields) => {
formValuesWrapper.innerHTML = `<pre>${JSON.stringify(fields, null, 4)}</pre>`
});
const inputs = [...document.querySelectorAll('input')];
inputs.map((input) => {
input.addEventListener('input', (e) => {
formState.updateField({
name: e.target.name,
value: e.target.value
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment