Skip to content

Instantly share code, notes, and snippets.

@nickleefly
Created April 20, 2020 06:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickleefly/6464de4c0f669399a2407d0c9905bdb2 to your computer and use it in GitHub Desktop.
Save nickleefly/6464de4c0f669399a2407d0c9905bdb2 to your computer and use it in GitHub Desktop.
eventemitter
class MyEventEmitter {
constructor() {
this._events = {};
}
on(name, listener) {
if (!this._events[name]) {
this._events[name] = [];
}
this._events[name].push(listener);
}
removeListener(name, listenerToRemove) {
if (!this._events[name]) {
throw new Error(`Can't remove a listener. Event "${name}" doesn't exits.`);
}
const filterListeners = (listener) => listener !== listenerToRemove;
this._events[name] = this._events[name].filter(filterListeners);
}
emit(name, data) {
if (!this._events[name]) {
throw new Error(`Can't emit an event. Event "${name}" doesn't exits.`);
}
const fireCallbacks = (callback) => {
callback(data);
};
this._events[name].forEach(fireCallbacks);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment