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

The Subject Interface

Understand the subject's responsibilities: maintaining observer lists, adding/removing observers, and triggering notifications.

The Subject Interface

What you'll learn: How a subject manages its observers and coordinates notifications in the Observer pattern.

Core Responsibilities

In the Observer pattern, the subject (or "observable") is the object being watched. Think of it like a newsletter service: the subject maintains a mailing list, allows people to subscribe or unsubscribe, and sends updates when new content is published.

The subject interface typically handles three key responsibilities:

1. Maintaining the Observer List

The subject keeps track of all registered observers, usually in an array or Set. This is its "subscriber list" that it references whenever something changes.

2. Adding and Removing Observers

The subject provides methods (commonly called subscribe/attach and unsubscribe/detach) that let observers join or leave the notification list. This gives observers control over when they want to receive updates.

3. Triggering Notifications

When the subject's state changes, it loops through its observer list and calls a notification method on each one (typically update() or notify()). This is how the subject broadcasts changes to all interested parties without knowing specific details about what each observer will do with that information.

The Interface Pattern

While JavaScript doesn't have formal interfaces, a typical subject implements this contract:

  • attach(observer) – adds an observer to the list
  • detach(observer) – removes an observer from the list
  • notify(data) – alerts all observers of a change

This separation of concerns means the subject focuses solely on when to notify, while observers decide how to react.

Key Takeaway: The subject interface defines a simple but powerful contract: maintain a list of observers, let them subscribe/unsubscribe, and broadcast notifications when state changes occur.