-
-
Save sanjayabc1234/390958381b55d94c839288057804cd66 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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