Skip to content

Instantly share code, notes, and snippets.

@rosputniy
Forked from PierfrancescoSoffritti/eventBus.js
Created September 14, 2018 17:27
Show Gist options
  • Save rosputniy/cba1b0dba1e5920878e7bb617f2cee08 to your computer and use it in GitHub Desktop.
Save rosputniy/cba1b0dba1e5920878e7bb617f2cee08 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