Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
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));
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!