The Observer Pattern seems like alot of overhead for what is essentially a grouped function call
See the CodePen link on article the-observer-pattern-in-javascript-explained
Please "try" to ignore the lack of non-DRY code in the example.
While this does the same thing just simpler Forked CodePen Here
I realize there is no subscribe/unsubscribe methods but add/removing from the toNotify array is similar.
Codepen Code:
const input = document.querySelector('.js-input');
const p1 = document.querySelector('.js-p1');
const p2 = document.querySelector('.js-p2');
const p3 = document.querySelector('.js-p3');
const toNotify = [p1, p2, p3]
function notify(text) {
toNotify.forEach(update => update.textContent = text)
}
input.addEventListener('keyup', e => {
notify(e.target.value);
});
The code is easier to read, code, and reason about.
However, I may be missing the point of the observer pattern and my humble example would break in other cases where the observer pattern would triumph and kick my example to the curb. I'm guessing classes, state management?
If you can let me know what I'm missing and/or have some examples of where the observer pattern really shines that would be great too
Aucun commentaire:
Enregistrer un commentaire