The Observer Pattern
You'll learn how to notify multiple parts of your code automatically when something changes, without tight coupling.
What Is the Observer Pattern?
The Observer Pattern defines a one-to-many dependency between objects. When one object (the "subject") changes state, all its dependent objects (the "observers") are notified and updated automatically. Think of it like a newsletter subscription: when the publisher has news, all subscribers receive it without the publisher needing to know who they are individually.
How It Works
The subject maintains a list of observers and provides methods to add or remove them. When something important happens, the subject loops through its observers and calls a notification method on each one.
function createSubject() {
const observers = [];
return {
subscribe(observer) {
observers.push(observer);
},
unsubscribe(observer) {
const index = observers.indexOf(observer);
if (index > -1) observers.splice(index, 1);
},
notify(data) {
observers.forEach(observer => observer.update(data));
}
};
}
const newsPublisher = createSubject();
const emailSubscriber = {
update(news) {
console.log(`Email sent: ${news}`);
}
};
const smsSubscriber = {
update(news) {
console.log(`SMS sent: ${news}`);
}
};
newsPublisher.subscribe(emailSubscriber);
newsPublisher.subscribe(smsSubscriber);
newsPublisher.notify('Breaking: New pattern learned!');
// Email sent: Breaking: New pattern learned!
// SMS sent: Breaking: New pattern learned!
The beauty is that the publisher doesn't know how observers react—it just notifies them. Observers can be added or removed without changing the subject's code.
Key Takeaway: The Observer Pattern decouples the source of events from their handlers, enabling flexible one-to-many communication where observers automatically respond to state changes.