Skip to content

Instantly share code, notes, and snippets.

@oleh-zaporozhets
Last active October 24, 2021 06:34
Show Gist options
  • Save oleh-zaporozhets/0233a929c19d6dcf6ef38d993715e812 to your computer and use it in GitHub Desktop.
Save oleh-zaporozhets/0233a929c19d6dcf6ef38d993715e812 to your computer and use it in GitHub Desktop.
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