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));
}
4
  • So what is the question? Commented Jan 28, 2022 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. Commented Jan 28, 2022 at 19:56
  • 1
    developer.mozilla.org/en-US/docs/Web/Events/… triggering is off the elements, but you can reuse the Event() Can make an event target stackoverflow.com/questions/15308371/… Commented Jan 28, 2022 at 20:12
  • Thank you this works as well! Commented Jan 28, 2022 at 21:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.