'How to create simple global event/message bus in javascript?

I am writing vanilla javascript project. I have multiple independent components. I like them to communicate without coupling them. Event based message bus is ideal for me. I implemented something trivial like following and I would like to ask whether is there any existing library that can do this more efficiently or whether language itself provides any capabilities to achieve this or not?

PS: I do not have any dom events in this case. I would like to create my own events so that I can write components pretty generic and clean way. I think React has similar concept and I will check that later on but for now I like to use vanilla javascript.

Thanks!

// event message bus interface
define(function(require) {

  "use strict";

  function CustomEventDispatcher() {
    this._subscribers = {}

  CustomEventDispatcher.prototype.on = function(event, callback) {
    if(!this._subscribers[event])
      this._subscribers[event] = [];
    this._subscribers[event].push(callback);
  }

  CustomEventDispatcher.prototype.trigger = function(event, params) {
    if (this._subscribers[event]) {
      for (let i in this._subscribers[event]) {
        this._subscribers[event][i](params);
      }
    }
  }

  CustomEventDispatcher.Instance = null;

  CustomEventDispatcher.GetInstance = function () {
    if (!CustomEventDispatcher.Instance) {
      CustomEventDispatcher.Instance = new CustomEventDispatcher();
    }
    return CustomEventDispatcher.Instance;
  }

  return CustomEventDispatcher;

});

// UI interaction triggers or backend worker triggers event
let params = {
    new_dir : '/dat',
};
CustomEventDispatcher.GetInstance().trigger('onUpdateDataSource', params);

// Directory Module registers directory update events and updates itself
function DirectorLister() { 
  CustomEventDispatcher.GetInstance().on('onUpdateDirectoryListing', (params) => this.change_content(params));
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source