Question 85

Question

Explain how to implement a basic pub/sub system from scratch.

Answer

Here's how to build a simple pub/sub (publish-subscribe) system in JavaScript, allowing components to communicate asynchronously:

Core Concepts:

  • Publisher: An object that emits events or "messages" (the "publication").

  • Subscriber: An object that listens for specific events and executes code when they occur (the "subscription").

Implementation:

class PubSub {
  constructor() {
    this.events = {}; 
  }

  // Subscribe to an event
  subscribe(eventName, callback) {
    if (!this.events[eventName]) {
      this.events[eventName] = []; // Create a new list for this event if it doesn't exist
    }
    this.events[eventName].push(callback); 
  }

  // Publish an event (trigger notifications)
  publish(eventName, data) {
    if (this.events[eventName]) {
      const subscribers = this.events[eventName]; // Get the list of subscribers for this event
      subscribers.forEach(callback => callback(data)); // Call each subscriber's function with the provided data
    }
  }
}

// Usage Example:

const pubSub = new PubSub();

// Subscriber 1
pubSub.subscribe('message', (msg) => {
  console.log("Subscriber 1 received:", msg); 
});

// Subscriber 2
pubSub.subscribe('message', (msg) => {
  console.log("Subscriber 2 received:", msg); 
});

// Publisher
pubSub.publish('message', 'Hello from the publisher!'); 


Explanation:

  1. PubSub Class: This class manages all the events and subscribers.

    • events: An object where keys are event names (strings) and values are arrays of callback functions that listen for those events.

  2. subscribe(eventName, callback):

    • Takes an eventName and a callback function as arguments.

    • If the event doesn't exist yet, it creates a new array in the events object to store subscribers for that event.

    • Adds the callback to the appropriate array of subscribers.

  3. publish(eventName, data):

    • Takes an eventName and some optional data as arguments.

    • Checks if there are any subscribers for the given eventName.

    • If there are, it iterates through the array of subscribers and calls each callback function with the provided data.

Key Points:

  • Asynchronous Communication: Subscribers don't execute immediately when an event is published; they run later when their respective callbacks are called.

  • Loose Coupling: Publishers and subscribers don't directly know about each other. They only interact through events, making your code more modular and maintainable.

Last updated