Skip to content

Instantly share code, notes, and snippets.

@tmdesigned
Forked from PierfrancescoSoffritti/eventBus.js
Created October 6, 2018 12:17
Show Gist options
  • Select an option

  • Save tmdesigned/a59a2a1d8e51e704ac009f3b273e0b73 to your computer and use it in GitHub Desktop.

Select an option

Save tmdesigned/a59a2a1d8e51e704ac009f3b273e0b73 to your computer and use it in GitHub Desktop.
A simple implementation of an event bus in Javascript
function EventBus() {
const eventCallbacksPairs = [];
this.subscribe = function( eventType, callback ) {
const eventCallbacksPair = findEventCallbacksPair(eventType);
if(eventCallbacksPair)
eventCallbacksPair.callbacks.push(callback);
else
eventCallbacksPairs.push( new EventCallbacksPair(eventType, callback) );
}
this.post = function( eventType, args ) {
const eventCallbacksPair = findEventCallbacksPair(eventType);
if(!eventCallbacksPair) {
console.error("no subscribers for event " +eventType);
return;
}
eventCallbacksPair.callbacks.forEach( callback => callback(args) );
}
function findEventCallbacksPair(eventType) {
return eventCallbacksPairs.find( eventObject => eventObject.eventType === eventType );
}
function EventCallbacksPair( eventType, callback ) {
this.eventType = eventType;
this.callbacks = [callback];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment