Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda