JavaScript and TypeScript course ยท Module 5: Advanced JavaScript

Observer and Pub/Sub Pattern

8 min read ยท
In this lesson7

At the Jurassic Park control center, Robert Muldoon observes dozens of monitors simultaneously. "The problem is," he explains, "that every system - fences, cameras, motion sensors - must immediately react to changes in a dinosaur's status. But they can't keep polling (checking) the database all the time!" The solution is the Observer pattern - a mechanism where objects automatically notify interested parties about changes.

Problem: Tight Component Coupling

Without the Observer pattern, components must directly know and call each other. The function that reacts to an escape then becomes a switchboard that phones every system by hand:

// Problem: the alarm system knows ALL other systems
function onDinosaurEscaped(dinosaur) {
  // Must manually call each system
  fenceSystem.activateEmergency(dinosaur);
  cameraSystem.trackDinosaur(dinosaur);
  alarmSystem.soundAlert(dinosaur);
  gateSystem.lockAllGates();
  evacuationSystem.startEvacuation();
  // What if we add a new system? We have to modify this function!
}

Each new system requires modifying existing code. This violates the Open-Closed Principle, which says code should be open for extension but closed for modification.

Observer Pattern - Basics

In the Observer pattern we have two types of objects:

  • Subject (Observable) - an object that emits events (notifies about changes)
  • Observer - an object that listens for events and reacts

The subject is the park siren, and the observers are the rangers who signed up to hear it. The simplest implementation is an EventEmitter, which keeps a list of callback functions for every event name:

// Simple EventEmitter - the heart of the Observer pattern
class EventEmitter {
  constructor() {
    this.listeners = {};
  }

  // Register an observer (subscribe)
  on(event, callback) {
    if (!this.listeners[event]) {
      this.listeners[event] = [];
    }
    this.listeners[event].push(callback);
    return this; // Enables chaining
  }

  // Emit an event (notify observers)
  emit(event, ...args) {
    const callbacks = this.listeners[event];
    if (callbacks) {
      callbacks.forEach(callback => callback(...args));
    }
    return this;
  }

  // Remove an observer
  off(event, callback) {
    if (this.listeners[event]) {
      this.listeners[event] = this.listeners[event].filter(
        cb => cb !== callback
      );
    }
    return this;
  }

  // One-time subscription
  once(event, callback) {
    const wrapper = (...args) => {
      callback(...args);
      this.off(event, wrapper);
    };
    this.on(event, wrapper);
    return this;
  }
}

The listeners object is a registry: an event name leads to an array of functions. on() adds a function, and emit() calls all of them synchronously, in registration order. off() compares functions by reference, so you cannot detach an anonymous arrow function passed straight to on(). once() wraps the callback in a function that unregisters itself after the first call.

Application in Jurassic Park

DinosaurMonitor extends EventEmitter, so it gets on(), emit() and off() for free. It only takes care of dinosaur data and announcing changes:

// Dinosaur monitoring system based on EventEmitter
class DinosaurMonitor extends EventEmitter {
  constructor() {
    super();
    this.dinosaurs = new Map();
  }

  registerDinosaur(id, data) {
    this.dinosaurs.set(id, { ...data, status: "contained" });
    this.emit("dinosaur:registered", { id, ...data });
  }

  updateStatus(id, newStatus) {
    const dino = this.dinosaurs.get(id);
    if (!dino) return;

    const oldStatus = dino.status;
    dino.status = newStatus;

    this.emit("status:changed", { id, name: dino.name, oldStatus, newStatus });

    // Emit a special event for escapes
    if (newStatus === "escaped") {
      this.emit("dinosaur:escaped", { id, name: dino.name, species: dino.species });
    }
  }
}

The monitor knows nothing about fences, cameras or evacuation - it only knows it has to announce an event. On an escape it emits two: the general status:changed and the specific dinosaur:escaped.

Now each system connects to the monitor on its own, and we simulate a T-Rex escape:

// Creating the system
const monitor = new DinosaurMonitor();

// Registering observers - each system connects itself
monitor.on("dinosaur:escaped", (data) => {
  console.log(`FENCE ALARM: ${data.name} escaped! Activating electric fence.`);
});

monitor.on("dinosaur:escaped", (data) => {
  console.log(`CAMERA ALARM: Tracking ${data.name} (${data.species}) on cameras.`);
});

monitor.on("dinosaur:escaped", (data) => {
  console.log(`EVACUATION ALARM: Starting evacuation due to ${data.name} escape!`);
});

monitor.on("status:changed", (data) => {
  console.log(`LOG: ${data.name} changed status from "${data.oldStatus}" to "${data.newStatus}"`);
});

// Register and simulate
monitor.registerDinosaur("TREX-001", { name: "Rexy", species: "T-Rex" });
monitor.registerDinosaur("RAPTOR-01", { name: "Blue", species: "Velociraptor" });

// Simulate escape
monitor.updateStatus("TREX-001", "escaped");
// LOG: Rexy changed status from "contained" to "escaped"
// FENCE ALARM: Rexy escaped! Activating electric fence.
// CAMERA ALARM: Tracking Rexy (T-Rex) on cameras.
// EVACUATION ALARM: Starting evacuation due to Rexy escape!

The order of the printouts follows the order of emit() calls in updateStatus(): first the log, then the three alarms in registration order. A new system, drones for example, takes a single monitor.on(...) call, without touching the monitor class. That is the main advantage of the pattern: lower coupling between components.

Publish/Subscribe (Pub/Sub) Pattern

Pub/Sub extends the Observer pattern where communication happens through channels/topics instead of direct references. The sender publishes to a topic, and receivers subscribe to topics without knowing anything about each other:

class PubSub {
  constructor() {
    this.topics = {};
    this.subscriptionId = 0;
  }

  // Subscribe to a topic
  subscribe(topic, callback) {
    if (!this.topics[topic]) {
      this.topics[topic] = {};
    }

    const id = ++this.subscriptionId;
    this.topics[topic][id] = callback;

    // Return an unsubscribe function
    return () => {
      delete this.topics[topic][id];
    };
  }

  // Publish a message
  publish(topic, data) {
    if (!this.topics[topic]) return;

    Object.values(this.topics[topic]).forEach(callback => {
      callback(data);
    });
  }
}

Each subscription gets its own number, and subscribe() returns a function that cancels it. So there is no need to keep a reference to the callback, as there is with off().

The park's central bus handles two topics - security alerts and the feeding schedule:

// Central park communication system
const parkBus = new PubSub();

// Systems subscribe to topics they care about
const unsubFence = parkBus.subscribe("security:alert", (data) => {
  console.log(`Fence: Alert received - ${data.message}`);
});

parkBus.subscribe("security:alert", (data) => {
  console.log(`Command center: Level ${data.level} alert - ${data.message}`);
});

parkBus.subscribe("feeding:schedule", (data) => {
  console.log(`Kitchen: Prepare ${data.food} for ${data.dinosaur}`);
});

// Publishing events - the sender doesn't know who is listening
parkBus.publish("security:alert", {
  level: "HIGH",
  message: "Movement detected near sector C fence"
});

parkBus.publish("feeding:schedule", {
  dinosaur: "Rexy",
  food: "200kg beef",
  time: "14:00"
});

// Unsubscribe
unsubFence(); // Fence stops listening

The alert reaches the fence and the command center, while the feeding message goes only to the kitchen. After unsubFence() the fence stops receiving alerts, while the command center keeps listening. Names like security:alert are just a convention that groups topics together.

Practical Example: Notification System

Both ideas can be combined. ParkNotificationSystem extends EventEmitter with a history and a * channel that hears everything:

class ParkNotificationSystem extends EventEmitter {
  constructor() {
    super();
    this.history = [];
  }

  notify(channel, message, priority = "normal") {
    const notification = {
      channel,
      message,
      priority,
      timestamp: new Date().toISOString()
    };

    this.history.push(notification);
    this.emit(channel, notification);
    this.emit("*", notification); // Wildcard - all notifications
  }

  getHistory(channel) {
    if (channel) {
      return this.history.filter(n => n.channel === channel);
    }
    return [...this.history];
  }
}

The notify() method emits every notification twice: on the target channel and on the * channel. getHistory() without an argument returns a copy of the history, so nobody outside can clear it by accident.

The admin panel subscribes to the asterisk, and the security and maintenance systems to their own channels:

const notifications = new ParkNotificationSystem();

// Admin panel - listens to everything
notifications.on("*", (n) => {
  console.log(`[ADMIN] [${n.priority.toUpperCase()}] ${n.channel}: ${n.message}`);
});

// Security system - only alerts
notifications.on("security", (n) => {
  if (n.priority === "critical") {
    console.log(`RED ALARM: ${n.message}`);
  }
});

// Logging
notifications.on("maintenance", (n) => {
  console.log(`Maintenance: ${n.message}`);
});

// Usage
notifications.notify("security", "Camera failure in sector B", "normal");
notifications.notify("security", "T-Rex broke through fence!", "critical");
notifications.notify("maintenance", "Replace lab light bulbs", "low");

console.log("Alert history:", notifications.getHistory("security"));

The admin panel prints all three notifications, the red alarm appears only for the critical priority, and the alert history contains two entries from the security channel.

Observer vs Pub/Sub - When to Use Which?

FeatureObserverPub/Sub
CouplingSubject knows observersSender and receiver don't know each other
CommunicationDirectThrough channel/topic
Use whenOne object notifies a fewMany objects communicate loosely
ExampleForm notifying validatorsMicroservices exchanging messages

The key difference is the intermediary: in Observer the subject keeps the list of observers itself, while in Pub/Sub the parties meet only on the channel. Neither pattern is synchronous or asynchronous by definition - our implementations call callbacks synchronously, while in distributed systems Pub/Sub messages usually travel asynchronously through a broker.

Summary

Muldoon summarizes: "The Observer pattern is like the park's alarm system - you don't have to constantly check every sensor. Sensors will notify you themselves:"

  1. Observer - an object (Subject) notifies registered observers about changes
  2. EventEmitter - Observer implementation with on(), emit(), off() methods
  3. Pub/Sub - looser coupling through channels/topics, sender doesn't know receivers
  4. Decoupling - components don't have to directly know each other, they communicate through events

These patterns are the foundation of many libraries and frameworks - from Node.js (EventEmitter) through React (state management) to microservice architectures.

In a real project don't write an emitter from scratch: Node.js has a ready-made EventEmitter in the node:events module, and the browser has EventTarget with addEventListener(). You will meet observers built into the browser, such as IntersectionObserver, later in this location. In the lab below you will extend PubSub with a once() method.

Remember: with Observer, the sensors call the rangers - the rangers don't patrol the enclosures with a flashlight.

Code for this lesson: index.js
// The Observer and Pub/Sub patterns
// Jurassic Park - Notification system

console.log("=== EVENT EMITTER ===");

// A simple EventEmitter implementation
class EventEmitter {
  constructor() {
    this.listeners = {};
  }

  on(event, callback) {
    if (!this.listeners[event]) {
      this.listeners[event] = [];
    }
    this.listeners[event].push(callback);
    return this;
  }

  emit(event, ...args) {
    const callbacks = this.listeners[event];
    if (callbacks) {
      callbacks.forEach(callback => callback(...args));
    }
    return this;
  }

  off(event, callback) {
    if (this.listeners[event]) {
      this.listeners[event] = this.listeners[event].filter(
        cb => cb !== callback
      );
    }
    return this;
  }

  once(event, callback) {
    const wrapper = (...args) => {
      callback(...args);
      this.off(event, wrapper);
    };
    this.on(event, wrapper);
    return this;
  }
}

console.log("\n=== MONITORING SYSTEM ===");

// Dinosaur monitoring system
class DinosaurMonitor extends EventEmitter {
  constructor() {
    super();
    this.dinosaurs = new Map();
  }

  register(id, data) {
    this.dinosaurs.set(id, { ...data, status: "contained" });
    this.emit("registered", { id, ...data });
  }

  updateStatus(id, newStatus) {
    const dino = this.dinosaurs.get(id);
    if (!dino) return;
    const oldStatus = dino.status;
    dino.status = newStatus;
    this.emit("status:changed", { id, name: dino.name, oldStatus, newStatus });
    if (newStatus === "escaped") {
      this.emit("dinosaur:escaped", { id, name: dino.name, species: dino.species });
    }
  }
}

const monitor = new DinosaurMonitor();

// Registering observers
monitor.on("dinosaur:escaped", (data) => {
  console.log(`ALARM: ${data.name} escaped! Activating the fence.`);
});

monitor.on("dinosaur:escaped", (data) => {
  console.log(`CAMERAS: Tracking ${data.name} (${data.species}).`);
});

monitor.on("status:changed", (data) => {
  console.log(`LOG: ${data.name}: "${data.oldStatus}" -> "${data.newStatus}"`);
});

monitor.register("TREX-001", { name: "Rexy", species: "T-Rex" });
monitor.register("RAPTOR-01", { name: "Blue", species: "Velociraptor" });

console.log("\n--- Escape simulation ---");
monitor.updateStatus("TREX-001", "escaped");

console.log("\n=== PUB/SUB ===");

// The Publish/Subscribe pattern
class PubSub {
  constructor() {
    this.topics = {};
    this.subId = 0;
  }

  subscribe(topic, callback) {
    if (!this.topics[topic]) this.topics[topic] = {};
    const id = ++this.subId;
    this.topics[topic][id] = callback;
    return () => { delete this.topics[topic][id]; };
  }

  publish(topic, data) {
    if (!this.topics[topic]) return;
    Object.values(this.topics[topic]).forEach(cb => cb(data));
  }
}

const parkBus = new PubSub();

parkBus.subscribe("security:alert", (data) => {
  console.log(`Fence: Alert - ${data.message}`);
});

parkBus.subscribe("security:alert", (data) => {
  console.log(`Control center: Level ${data.level} - ${data.message}`);
});

const unsubFeeding = parkBus.subscribe("feeding", (data) => {
  console.log(`Kitchen: ${data.food} for ${data.dinosaur}`);
});

parkBus.publish("security:alert", {
  level: "HIGH",
  message: "Movement at the sector C fence"
});

parkBus.publish("feeding", {
  dinosaur: "Rexy",
  food: "200kg of beef"
});

// Unsubscribing
unsubFeeding();
console.log("\nAfter unsubscribing from feeding:");
parkBus.publish("feeding", { dinosaur: "Blue", food: "50kg of meat" });
// Nothing will be displayed

// TODO: Add a once() method to PubSub
// TODO: Create a notification system with an event history
console.log("\n=== Exercise ===");
console.log("Extend PubSub with a once() method - see the TODO");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is the main advantage of the Observer pattern compared to direct function calls?

  2. 2. Which EventEmitter method is used to register an observer (listen for an event)?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Create an EventEmitter with on(), emit(), off() methods and a park notification system.

  • Click in order

    Arrange the operation order in the Observer pattern:

  1. QuestionObserver Pattern - Basics
  2. QuestionEventEmitter Methods
  3. QuestionPub/Sub vs Observer
  4. Coding taskPractice: EventEmitter and Pub/Sub
  5. Click in orderOperation Order in the Observer Pattern

Useful articles