JavaScript Course
JavaScript
/
Advanced

Observer Pattern

Definition

A behavioral design pattern where an object (the Subject) maintains a list of its dependents (Observers) and automatically notifies them of any state changes, usually by calling one of their methods.

Explain Like I'm New

The Observer pattern is a YouTube channel. The Subject is the YouTuber. The Observers are the subscribers. The subscribers say 'Hey, let me know when you upload.' When the YouTuber uploads a video, they don't manually message every single person; the system iterates through the subscriber list and sends everyone a notification.

Real World Example

React's `useEffect` listening to state changes. Vue's reactivity system. Standard DOM event listeners (`element.addEventListener('click', fn)`).

Common Use Cases

  • •Event-driven architectures
  • •Decoupling complex UI updates

Interactive Example

class YouTubeChannel { // The Subject
  constructor() {
    this.subscribers = [];
  }

  subscribe(callback) {
    this.subscribers.push(callback);
    // Return an unsubscribe function
    return () => {
      this.subscribers = this.subscribers.filter(sub => sub !== callback);
    };
  }

  uploadVideo(title) {
    console.log(`Uploaded: ${title}. Notifying subs...`);
    // Notify all observers
    this.subscribers.forEach(callback => callback(title));
  }
}

const channel = new YouTubeChannel();

// Observer 1
const unsubAlice = channel.subscribe(video => console.log(`Alice got pinged: ${video}`));
// Observer 2
channel.subscribe(video => console.log(`Bob got pinged: ${video}`));

channel.uploadVideo("JS Patterns Explained"); 

// Alice unsubscribes
unsubAlice();

channel.uploadVideo("React Hooks"); // Only Bob gets pinged

Interview Questions

basic

  • What are the two main roles in the Observer pattern?

intermediate

  • What is the difference between the Observer pattern and the Pub-Sub pattern?

advanced

  • How do you prevent memory leaks when using the Observer pattern?

Flash Cards

Question

Observer vs Pub-Sub?

Click to reveal answer
Answer

In Observer, the Subject and the Observers know about each other tightly (the Subject holds the array of callbacks). In Pub-Sub, there is a middleman (the Event Bus or Broker). Publishers just throw events into the void, and Subscribers listen to the void. They never directly interact.

Question

How to prevent memory leaks?

Click to reveal answer
Answer

You MUST provide an `unsubscribe` or `removeObserver` method. If an Observer (like a UI component) is destroyed but forgets to unsubscribe, the Subject still holds a reference to it in its array, preventing garbage collection.