Skip to content

Instantly share code, notes, and snippets.

@ezzabuzaid
Created May 28, 2020 22:25
Show Gist options
  • Save ezzabuzaid/4bba17c2fdbaef1fa756ab65c511086e to your computer and use it in GitHub Desktop.
Save ezzabuzaid/4bba17c2fdbaef1fa756ab65c511086e to your computer and use it in GitHub Desktop.
Custom EventEmitter
class EventEmitter {
constructor() {
this.callbacks = {};
this.noEventYet = [];
}
addEventListener(eventName, callback) {
const callbacks = this.callbacks[eventName];
if (!Array.isArray(callbacks)) {
this.callbacks[eventName] = [];
}
callbacks.push(callback);
// Check if there was an event called before any callback registered
const indexOfNotYetEvent = this.noEventYet.indexOf(eventName);
if (indexOfNotYetEvent >= 0) {
callback();
}
this.noEventYet.slice(indexOfNotYetEvent, indexOfNotYetEvent + 1);
}
removeEventListener(eventName, callback) {
const callbacks = this.callbacks[eventName];
if (Array.isArray(callbacks)) {
const indexOfcallback = callbacks.findIndex(alreadyRegesriedCallback => {
return alreadyRegesriedCallback === callback;
});
callbacks.slice(indexOfcallback, indexOfcallback + 1);
} else {
throw new Error(`Event ${eventName} is not exist`);
}
}
dispatchEvent(eventName) {
const callbacks = this.callbacks[eventName];
if (Array.isArray(callbacks)) {
callbacks.forEach(callback => {
callback();
});
} else {
// throw new Error(`Event ${eventName} is not exist`);
this.noEventYet.push(eventName);
}
}
}
const eventEmitter = new EventEmitter();
function logClick() {
log('Log click');
}
eventEmitter.addEventListener('click', logClick);
eventEmitter.removeEventListener('click', logClick);
eventEmitter.addEventListener('load_todo', () => {});
eventEmitter.addEventListener('load_todo', () => {});
eventEmitter.dispatchEvent('load_todo');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment