0
0
JavascriptConceptBeginner · 3 min read

Observer Pattern in JavaScript: What It Is and How It Works

The observer pattern in JavaScript is a design pattern where an object (called the subject) maintains a list of dependents (observers) and notifies them automatically of any state changes. It helps create a clear communication system where observers react to changes without tightly coupling to the subject.
⚙️

How It Works

Imagine you have a newsletter service where people can subscribe to get updates. The newsletter is the subject, and the subscribers are the observers. When the newsletter publishes a new issue, it automatically sends the update to all subscribers.

In JavaScript, the observer pattern works similarly. The subject keeps a list of observers (functions or objects) that want to know when something changes. When the subject's state changes, it notifies all observers by calling their update methods or functions. This way, observers stay in sync without the subject needing to know details about them.

This pattern helps keep code organized and flexible, especially when many parts of a program need to react to changes in data or events.

💻

Example

This example shows a simple observer pattern where a Subject class manages observers and notifies them when its state changes.

javascript
class Subject {
  constructor() {
    this.observers = [];
  }

  subscribe(observer) {
    this.observers.push(observer);
  }

  unsubscribe(observer) {
    this.observers = this.observers.filter(obs => obs !== observer);
  }

  notify(data) {
    this.observers.forEach(observer => observer.update(data));
  }
}

class Observer {
  constructor(name) {
    this.name = name;
  }

  update(data) {
    console.log(`${this.name} received update: ${data}`);
  }
}

// Usage
const subject = new Subject();
const observer1 = new Observer('Observer 1');
const observer2 = new Observer('Observer 2');

subject.subscribe(observer1);
subject.subscribe(observer2);

subject.notify('Hello Observers!');

subject.unsubscribe(observer1);

subject.notify('Second update');
Output
Observer 1 received update: Hello Observers! Observer 2 received update: Hello Observers! Observer 2 received update: Second update
🎯

When to Use

Use the observer pattern when you want to keep different parts of your program updated automatically without tight connections between them. It is great for event handling, user interface updates, or any situation where multiple objects need to react to changes.

For example, in a chat app, when a new message arrives, the message list, notification badge, and sound alert can all update independently by observing the message source. This keeps your code clean and easy to maintain.

Key Points

  • The subject keeps a list of observers and notifies them on changes.
  • Observers implement an update method to react to notifications.
  • It decouples the subject from observers, improving flexibility.
  • Commonly used in event-driven programming and UI updates.

Key Takeaways

The observer pattern lets objects watch and react to changes in another object automatically.
It helps keep code flexible by decoupling the subject from its observers.
Use it when multiple parts of your app need to update based on shared data or events.
Observers subscribe to the subject and get notified through an update method.
This pattern is common in event handling and UI programming.