Implementing the Observer Pattern in JavaScript

Introduction to the Observer Pattern

Welcome back! We're continuing our exploration of Behavioral Patterns. In this lesson, we will delve into the Observer Pattern, another fundamental pattern that emphasizes object communication and responsibility distribution. This pattern allows an object, known as the subject, to maintain a list of its dependents, called observers, and notify them automatically of any state changes, usually by calling one of their methods.

Previously, we looked at the Command Pattern, which encapsulates a request as an object. Now, let's build on that knowledge and explore how the Observer Pattern facilitates communication between objects in a seamless and efficient manner.

Core Components of the Observer Pattern

Let's break down the process into clear steps to implement the Observer Pattern.

Step 1: Define the Observer

Start by defining the Observer class that lays out the interface for receiving updates.

class Subscriber {
    update(news) {
        throw new Error('You have to implement the method update!');
    }
}

In this code snippet, the Subscriber class defines the update method. This method will be called by the subject to notify subscribers of any updates.

Step 2: Create the Subject

Next, create the NewsPublisher class, which acts as the Subject. This class maintains a list of subscribers and provides methods to add and remove subscribers, as well as to notify them.

class NewsPublisher {
    constructor() {
        this.subscribers = [];
    }

    addSubscriber(subscriber) {
        this.subscribers.push(subscriber);
    }

    removeSubscriber(subscriber) {
        const index = this.subscribers.indexOf(subscriber);
        if (index !== -1) {
            this.subscribers.splice(index, 1);
        }
    }

    publish(news) {
        this.subscribers.forEach(subscriber => subscriber.update(news));
    }
}

The NewsPublisher class has three methods: addSubscriber to add a new subscriber, removeSubscriber to remove an existing subscriber, and publish to notify all subscribers of new news.

Step 3: Implement a Concrete Observer

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal