Created
April 11, 2021 19:07
-
-
Save leonidkuznetsov18/502370dc8630348df4c547263c1272ec to your computer and use it in GitHub Desktop.
Event Bus Typescript
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
| import { EventEmitter } from 'eventemitter3'; | |
| type ListenerFn = (...args: Array<any>) => void; | |
| class EventBus { | |
| public eventEmitter: EventEmitter; | |
| /** | |
| * Initiate the event emitter | |
| */ | |
| constructor() { | |
| this.eventEmitter = new EventEmitter(); | |
| } | |
| /** | |
| * Adds the listener function to the end of the listeners array for | |
| * the event named eventName. No checks are made to see if the listener | |
| * has already been added. Multiple calls passing the same combination of | |
| * eventName and listener will result in the listener being added, and called, | |
| * multiple times. | |
| * | |
| * @param {string} eventName | |
| * @param {function} listener | |
| * @param {any} context | |
| */ | |
| public addEventListener(eventName: string, listener: ListenerFn, context?: any): void { | |
| this.eventEmitter.on(eventName, listener, context); | |
| } | |
| /** | |
| * Removes the specified listener from the listener array for the event named eventName. | |
| * | |
| * @param {string} eventName | |
| * @param {function} listener | |
| * @param {any} context | |
| * @param {boolean} once | |
| */ | |
| public removeEventListener(eventName: string, listener?: ListenerFn, context?: any, once?: boolean): void { | |
| this.eventEmitter.off(eventName, listener, context, once); | |
| } | |
| /** | |
| * Synchronously calls each of the listeners registered for the event | |
| * named eventName, in the order they were registered, | |
| * passing the supplied arguments to each. | |
| * | |
| * @param {string} eventName | |
| * @param {array} args | |
| */ | |
| public emit(eventName: string, ...args: Array<any>): void { | |
| this.eventEmitter.emit(eventName, ...args); | |
| } | |
| /** | |
| * Returns the event emitter | |
| * Used for testing purpose and avoid using this during development | |
| */ | |
| public getEventEmitter(): EventEmitter { | |
| return this.eventEmitter; | |
| } | |
| /** | |
| * Adds a one-time listener function for the event named eventName. | |
| * The next time eventName is triggered, this listener is removed and then invoked. | |
| * | |
| * @param {string} eventName | |
| * @param {ListenerFn} listener | |
| * @param {any} context | |
| */ | |
| public once(eventName: string, listener: ListenerFn, context?: any): void { | |
| this.eventEmitter.once(eventName, listener, context); | |
| } | |
| } | |
| export const eventBusClient = new EventBus(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment