Created
January 10, 2022 02:01
-
-
Save vagnercardosoweb/aa563de0a5eb19f134008302800815c3 to your computer and use it in GitHub Desktop.
event manager in pure js
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
| type Listener<T = any> = () => Promise<T> | T; | |
| class EventManager { | |
| protected listeners: Record<string, Listener[]> = {}; | |
| public on<T = any>(eventName: string, listener: Listener<T>) { | |
| if (typeof this.listeners[eventName] !== 'object') { | |
| this.listeners[eventName] = []; | |
| } | |
| this.listeners[eventName].push(listener); | |
| return listener; | |
| } | |
| public emit(eventName: string, ...args: any[]) { | |
| if (typeof this.listeners[eventName] !== 'object') { | |
| return; | |
| } | |
| this.listeners[eventName].forEach(listener => { | |
| try { | |
| listener.apply(this, args); | |
| } catch { | |
| throw new Error(`Error while emitting event ${eventName}`); | |
| } | |
| }); | |
| } | |
| public remove(eventName: string, listener: Listener) { | |
| if (typeof this.listeners[eventName] !== 'object') { | |
| return; | |
| } | |
| const listenerIndex = this.listeners[eventName].indexOf(listener); | |
| if (listenerIndex !== -1) { | |
| this.listeners[eventName].splice(listenerIndex, 1); | |
| } | |
| if (this.listeners[eventName].length === 0) { | |
| delete this.listeners[eventName]; | |
| } | |
| } | |
| } | |
| const eventManager = new EventManager(); | |
| export default eventManager; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment