Course contentsShow
← JavaScript
Lesson 1844 of 2,72338. Object-Oriented PatternsFree lesson

The Pub/Sub Pattern

Decouple publishers and subscribers with an event channel, allowing loose coupling.

The Pub/Sub Pattern

What you'll learn: How to decouple publishers and subscribers using an event channel for maximum flexibility.

The Pub/Sub (Publish/Subscribe) pattern is similar to the Observer pattern but with a key difference: publishers and subscribers don't know about each other. Instead, they communicate through an intermediary called an event channel or event bus.

How It Works

Imagine a radio station (publisher) broadcasting music. Listeners (subscribers) tune into specific frequencies without the station knowing who's listening. A radio tower (event bus) handles the transmission. Listeners can come and go, and the station just keeps broadcasting.

In code, the event bus sits between publishers and subscribers:

// Simple Event Bus
const eventBus = {
  events: {},
  
  subscribe(event, callback) {
    if (!this.events[event]) {
      this.events[event] = [];
    }
    this.events[event].push(callback);
  },
  
  publish(event, data) {
    if (!this.events[event]) return;
    this.events[event].forEach(callback => callback(data));
  }
};

// Subscribers (don't know who publishes)
eventBus.subscribe('user:login', user => {
  console.log('Analytics:', user.name);
});

eventBus.subscribe('user:login', user => {
  console.log('UI: Welcome,', user.name);
});

// Publisher (doesn't know who's listening)
function login(username) {
  const user = { name: username };
  eventBus.publish('user:login', user);
}

login('Alice');
// Analytics: Alice
// UI: Welcome, Alice

Pub/Sub vs Observer

The Observer pattern creates direct connections—observers hold references to subjects. Pub/Sub adds an intermediary, creating loose coupling. Components can be added or removed without affecting others.

Key Takeaway: The Pub/Sub pattern uses an event channel to completely decouple publishers from subscribers, making systems more modular and flexible than direct observer relationships.