JavaScript EventBus Example - Subscribe/Publish Listeners

In this article, I show you how to implement a simple event bus in Javascript. EventBus is an extremely useful tool for decoupling the components of your apps.
An event bus implements the publisher/subscriber pattern. It can be used to decouple the components of an application so that a component can react to events fired from another component without them having direct dependencies with each other. They only need to know the event bus.
Every subscriber can subscribe to a specific event. A subscriber will be notified when the event it subscribes to is published on the event bus.
A publisher can publish events on the event bus when something happens.
For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this article, and run it by pressing the Enter/Return key.

Event bus implementation

Subscribe

In this implementation, a subscriber is a simple listener function or a callback function. The function is called when the event of interest is published in the event bus.
this.addEventListener = function(eventName, listener) {
 if (!eventTopics[eventName] || eventTopics[eventName].length < 1) {
  eventTopics[eventName] = [];
 }
 eventTopics[eventName].push(listener);
};

Publisher

The publish function takes as arguments the event and the arguments for the subscribers.
If there are no subscribers for eventType, it just returns.
Otherwise, it iterates over the subscribers registered for eventType and calls each function, passing the provided arguments.
this.emitEventListeners = function(eventName, params) {
 if (!eventTopics[eventName] || eventTopics[eventName].length < 1)
  return;
 eventTopics[eventName].forEach(function(listener) {
  listener(!!params ? params : {});
 });
}
Note that we are using forEach() function to iterate over subscribers.

Remove Subscriber

You can also remove subscriber that registered for a specific event type.
this.removeListener = function(eventName, listener) {
 if (!eventTopics[eventName] || eventTopics[eventName].length < 1)
  return;
 // delete listener by event name
 delete eventTopics[eventName];
};

this.getListener = function(eventName){
 return eventTopics[eventName];
}

Usage

In this example, we are subscribing two callback functions to single event1 using addEventListener() function. When we publish some data using emitEventListeners() function should notify all the subscribers that are subscribed to "event1".
function test(){

 var eventBus = new EventBus();
 var data1 = "some data for event1";
 var data2 = "some data for event2";
 // add listener to event1
 eventBus.addEventListener("event1", function(data){
  console.log("listener1 listen event1 -> " + data);
 });
 
 // add listener to event1
 eventBus.addEventListener("event1", function(data){
  console.log("listener2 listen event1 -> " + data);
 });

 // add listener to event2
 eventBus.addEventListener("event2", function(data){
  console.log("listener1 listen event2 -> " + data);
 });
 
 // add listener to event2
 eventBus.addEventListener("event2", function(data){
  console.log("listener2 listen event2 -> " + data);
 });

 
 eventBus.emitEventListeners("event1", data1);
 eventBus.emitEventListeners("event2", data2);
}

test();

Complete Code and Output

/**
 *  Create an Event Bus object which has the registration and publishing API.
 *  addEventListener and emitEventListeners functions 
 *  lets the subscriber and publisher to subscribe and publish on events respectively.
 */

function EventBus() {
 var eventTopics = {};

 this.addEventListener = function(eventName, listener) {
  if (!eventTopics[eventName] || eventTopics[eventName].length < 1) {
   eventTopics[eventName] = [];
  }
  eventTopics[eventName].push(listener);
 };

 this.emitEventListeners = function(eventName, params) {
  if (!eventTopics[eventName] || eventTopics[eventName].length < 1)
   return;
  eventTopics[eventName].forEach(function(listener) {
   listener(!!params ? params : {});
  });
 }

 this.removeListener = function(eventName, listener) {
  if (!eventTopics[eventName] || eventTopics[eventName].length < 1)
   return;
  // delete listener by event name
  delete eventTopics[eventName];
 };

 this.getListener = function(eventName){
  return eventTopics[eventName];
 }
} //END EventBus




function test(){

 var eventBus = new EventBus();
 var data1 = "some data for event1";
 var data2 = "some data for event2";
 // add listener to event1
 eventBus.addEventListener("event1", function(data){
  console.log("listener1 listen event1 -> " + data);
 });
 
 // add listener to event1
 eventBus.addEventListener("event1", function(data){
  console.log("listener2 listen event1 -> " + data);
 });

 // add listener to event2
 eventBus.addEventListener("event2", function(data){
  console.log("listener1 listen event2 -> " + data);
 });
 
 // add listener to event2
 eventBus.addEventListener("event2", function(data){
  console.log("listener2 listen event2 -> " + data);
 });

 
 eventBus.emitEventListeners("event1", data1);
 eventBus.emitEventListeners("event2", data2);
}

test();
Output:
listener1 listen event1 -> some data for event1
listener2 listen event1 -> some data for event1
listener1 listen event2 -> some data for event2
listener2 listen event2 -> some data for event2

Comments