🏗️Observer Pattern
Also known as Observer, Listener Pattern, Event Listener
One object keeps a list of others. It tells them all when it changes.
Think of it like
Think of it like a shop's mailing list. When new stock comes in, all on the list get told.
Example
Lucy's page has a button. Two pieces of code each call addEventListener on it. When the button is clicked, both run.
Why it matters
The watched object does not need to know who is listening. So new listeners can join with ease.
Definition
Example code
javascript
button.addEventListener('click', () => save());
button.addEventListener('click', () => track('saved'));
// one click: both functions runCommon mistake
Key takeaways
- 1One tells many. On every change.
- 2Sign up to listen. Add to the list.
- 3Remember to leave. Or memory leaks.