Pub Sub I

Showcase the working of publisher-subscriber pattern in JavaScript. This works similar to the addEventListener in JavaScript where a callback function is assigned to the event, and that callback function will be invoked when the event is fired. removeEventListener can be used to remove the listener.

Similar to this create a function Event that will have three methods

  1. subscribe(fn): subscribes the function to the event.
  2. unsubscribe(fn): unsubscribes the function from the event.
  3. fire(data): when event is fired or published all the subscribed function should be invoked with the data.
class Event {
  constructor() {
    this.events = [];
  }

  subscribe = (fn) => {
    this.events.push(fn);
  };

  unsubscribe = (fn) => {
    this.events = this.events.filter((Fn) => Fn !== fn);
  };

  fire = (data) => {
    this.events.forEach((Fn) => {
      Fn(data);
    });
  };
}

const event1 = function (item) {
  console.log("Fired: " + item);
};

const event2 = function (item) {
  console.log("Moved: " + item);
};

const event = new Event();

event.subscribe(event1);
event.fire("event #1");
event.unsubscribe(event1);
event.fire("event #2");
event.subscribe(event1);
event.subscribe(event2);
event.fire("event #3");

// Fired: event #1
// Fired: event #3
// Moved: event #3