Created
May 17, 2020 04:23
-
-
Save Ifmr24/86003c256bd4d5328af1805635507ac8 to your computer and use it in GitHub Desktop.
JS Patron Observador
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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