Skip to content

Instantly share code, notes, and snippets.

@aandrewww
Created April 29, 2020 14:58
Show Gist options
  • Save aandrewww/6846d72d675ba1991727313a0caf0454 to your computer and use it in GitHub Desktop.
Save aandrewww/6846d72d675ba1991727313a0caf0454 to your computer and use it in GitHub Desktop.
EventEmmiterManager
import _ from 'lodash';
export default class EventEmitterManager {
constructor() {
this.handlerCallbacks = {};
}
listenOn(eventName, handlerCallback) {
if (!this.handlerCallbacks[eventName]) {
this.handlerCallbacks[eventName] = [];
}
if (_.indexOf(this.handlerCallbacks[eventName], handlerCallback) === -1) {
this.handlerCallbacks[eventName].push(handlerCallback);
}
}
emitEvent(eventName, params = {}) {
if (this.handlerCallbacks[eventName]) {
(this.handlerCallbacks[eventName]).forEach(callback => callback(params));
}
}
removeListeners(eventName) {
delete this.handlerCallbacks[eventName];
}
removeListener(eventName, listener) {
const handlers = this.handlerCallbacks[eventName];
if (handlers) {
(handlers).forEach((handler, index) => {
if (handler === listener) {
handlers.splice(index, 1);
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment