DEV Community

Cover image for Publisher–Subscriber Pattern in JavaScript (Simple Implementation)
Bobby Sadhwani
Bobby Sadhwani

Posted on

Publisher–Subscriber Pattern in JavaScript (Simple Implementation)

The Publisher–Subscriber (Pub-Sub) pattern is a messaging pattern where senders (publishers) do not directly communicate with receivers (subscribers).

Instead, subscribers register their interest, and the publisher notifies them when something happens.

Below is a clean, minimal JavaScript implementation using classes.


1. Publisher (Host)

The entity that maintains a list of subscribers and notifies them of events.

Responsibilities

  • subscribe(observer) → Add a new subscriber to the list
  • unsubscribe(observer) → Remove a subscriber from the list
  • fire() → Call all subscribed functions, optionally forcing what this should be inside those functions, and pass them some data

2. Subscriber (Observer)

The entities that want to be notified when certain events occur.


Implementation

class Host {
  constructor() {
    this.observers = [];
  }

  // subscribe an observer
  subscribe(observer) {
    this.observers.push(observer);
  }

  // unsubscribe an observer
  // observer is a function, so its reference is used to identify it
  unsunscribe(observer) {
    this.observers = this.observers.filter((obs) => obs !== observer);
  }

  // fire an event to all observers
  // call method is used to set the scope of the observer function call
  // In browser scope would be window, in Node.js it would be global
  fire(scope, data) {
    const context = scope || global;
    this.observers.forEach((obs) => obs.call(context, data));
  }
}

// Host / Publisher instance
const host = new Host();

// Observer / Subscriber functions
function subscriberOne(data) {
  console.log("Subscriber One received data:", data);
}

function subscriberTwo(data) {
  console.log("Subscriber Two received data:", data);
}

// Subscribe observers to the host
host.subscribe(subscriberOne);
host.subscribe(subscriberTwo);

// Fire event to all subscribers
host.fire(null, "Your first message");

// Unsubscribe subscriberOne
host.unsunscribe(subscriberOne);
Enter fullscreen mode Exit fullscreen mode

Final Words

And that’s it for this blog.

I hope you’ve found this blog a good referencing resource and thank you for reading.

If this blog was helpful, please do like, comment and share. Thanks, see you in the next blog.✌️

Top comments (0)