Course contentsShow
← JavaScript
Lesson 2109 of 2,72344. Reactive PatternsFree lesson

Implementing a Simple Subject

Build a basic subject class with methods to subscribe, unsubscribe, and notify all observers.

Implementing a Simple Subject

You'll learn how to build a subject class that can register, remove, and notify multiple observers.

The Core Idea

A subject maintains a list of observers and provides methods to manage them. Think of it like a newsletter service: subscribers sign up (subscribe), can cancel (unsubscribe), and receive updates when news arrives (notify). The subject doesn't need to know what each observer does with the notification—it just needs to deliver it.

Building the Subject Class

Your subject needs three key responsibilities:

1. Store observers — Keep a collection (typically an array) of all registered observer objects.

2. Subscribe method — Add new observers to the list. Should prevent duplicates if the same observer subscribes twice.

3. Unsubscribe method — Remove an observer from the list when they no longer want updates.

4. Notify method — Loop through all observers and call their update() method (or whichever method your observer interface defines), passing along any relevant data.

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

  subscribe(observer) {
    if (!this.observers.includes(observer)) {
      this.observers.push(observer);
    }
  }

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

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

When you call notify(), every registered observer receives the data. This decouples the subject from knowing what observers do—it just broadcasts the message.

Key Takeaway: A subject manages observer subscriptions and broadcasts notifications to all registered observers through a simple, centralized notification mechanism.