0

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));
}
Validus Oculus
  • 2,756
  • 1
  • 25
  • 34
  • So what is the question? – epascarello Jan 28 '22 at 19:47
  • @epascarello I thought question is clear but let me reiterate. I have implemented above code but given javascript has dom events already, I thought language might have generic event support that I can use. I could not find it so I wanted to ask what experienced web developers would suggest for this case. I hope it is clear. – Validus Oculus Jan 28 '22 at 19:56
  • 1
    https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events triggering is off the elements, but you can reuse the Event() Can make an event target https://stackoverflow.com/questions/15308371/custom-events-model-without-using-dom-events-in-javascript – epascarello Jan 28 '22 at 20:12
  • Thank you this works as well! – Validus Oculus Jan 28 '22 at 21:18

0 Answers0