Observer Design Pattern Explained
The Observer pattern lets an object (the subject) notify a list of dependent objects (observers) automatically whenever its state changes, without the subjec...
Published October 6, 2026
The Observer pattern lets one object (the subject) notify many dependent objects (observers) automatically when its state changes, without the subject knowing who they are. It is the idea behind events, listeners and reactive streams.
The concept
Observers subscribe to the subject. When something happens the subject loops over subscribers and calls them.
This decouples the sender from the receivers. The danger is forgetting to unsubscribe, causing memory leaks and surprise updates.
Publish to subscribers
Practical examples
Minimal implementation
class Subject {
#subs = new Set()
subscribe(fn) { this.#subs.add(fn); return () => this.#subs.delete(fn) }
emit(data) { this.#subs.forEach(fn => fn(data)) }
}
const s = new Subject()
const off = s.subscribe(d => console.log('got', d))
s.emit(1); off()DOM events
el.addEventListener('click', onClick)
el.removeEventListener('click', onClick)Node EventEmitter
import { EventEmitter } from 'events'
const e = new EventEmitter()
e.on('order', o => console.log(o))
e.emit('order', { id: 1 })Common mistakes
- Not unsubscribing observers.
- Emitting inside an observer and creating loops.
- Relying on observer order.
Key takeaways
- Subject notifies subscribers.
- Decouples producers from consumers.
- Always provide unsubscribe.
FAQ
Observer vs Pub/Sub?
Pub/Sub adds a broker between publisher and subscribers so they never know each other.
Where do I see it daily?
DOM events, Redux subscriptions, RxJS.