Last active
October 24, 2021 06:34
-
-
Save oleh-zaporozhets/0233a929c19d6dcf6ef38d993715e812 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 EventEmitter implements IEventEmitter { | |
private readonly events: Record<string, Function[]>; | |
public constructor() { | |
this.events = {}; | |
} | |
public on(name: string, listener: Function) { | |
if (!this.events[name]) { | |
this.events[name] = []; | |
} | |
this.events[name].push(listener); | |
} | |
public removeListener(name: string, listenerToRemove: Function) { | |
if (!this.events[name]) { | |
throw new Error(`Can't remove a listener. Event "${name}" doesn't exits.`); | |
} | |
const filterListeners = (listener: Function) => listener !== listenerToRemove; | |
this.events[name] = this.events[name].filter(filterListeners); | |
} | |
public emit(name: string, data: any) { | |
if (!this.events[name]) { | |
throw new Error(`Can't emit an event. Event "${name}" doesn't exits.`); | |
} | |
const fireCallbacks = (callback: Function) => { | |
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