Last active
September 3, 2021 12:04
-
-
Save yatishbalaji/9e773a8346ae0b7d9d82ee935358f689 to your computer and use it in GitHub Desktop.
custom JS pubsub
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
| export interface IPubSubOptions { | |
| maxListeners?: number; | |
| } | |
| export class PubSub { | |
| private maxListeners: number; | |
| private listenerCount: number; | |
| private eventListeners: Map<string, Function[]>; | |
| constructor(options: IPubSubOptions) { | |
| this.maxListeners = options.maxListeners || 1000; | |
| this.listenerCount = 0; | |
| } | |
| setMaxListeners(listenerCount: number): PubSub { | |
| this.maxListeners = listenerCount; | |
| return this; | |
| } | |
| private setListenerCount(count: number): void { | |
| this.listenerCount = count; | |
| } | |
| getListenerCount(): number { | |
| return this.listenerCount; | |
| } | |
| getEventListenerCount(event: string): number { | |
| return (this.eventListeners.get(event) || []).length; | |
| } | |
| on(event: string, fn: Function): PubSub { | |
| if (this.getListenerCount() === this.maxListeners) { | |
| console.log('Number of listeners exceded maxListeners set'); | |
| return this; | |
| } | |
| const listeners = this.eventListeners.get(event) || []; | |
| listeners.push(fn); | |
| this.eventListeners.set(event, listeners); | |
| this.setListenerCount(this.listenerCount + 1); | |
| return this; | |
| } | |
| off(event: string, fn: Function): PubSub { | |
| const listeners = this.eventListeners.get(event); | |
| if (!listeners) return this; | |
| const len = listeners.length; | |
| for (let i = 0; i < len; i++) { | |
| if (listeners[i] === fn) { | |
| listeners.splice(i, 1); | |
| this.setListenerCount(this.listenerCount - 1); | |
| break; | |
| } | |
| } | |
| return this; | |
| } | |
| once(event: string, fn: Function): PubSub { | |
| if (this.getListenerCount() === this.maxListeners) { | |
| console.log('Number of listeners exceded maxListeners set'); | |
| return this; | |
| } | |
| const listeners = this.eventListeners.get(event) || []; | |
| const innerFn = (...args: IArguments[]) => { | |
| fn(...args); | |
| this.off(event, fn); | |
| }; | |
| listeners.push(innerFn); | |
| this.eventListeners.set(event, listeners); | |
| this.setListenerCount(this.listenerCount + 1); | |
| return this; | |
| } | |
| emit(event: string, ...args: IArguments[]): boolean { | |
| const listeners = this.eventListeners.get(event); | |
| if (!listeners) return false; | |
| listeners.forEach(fn => fn(...args)); | |
| return true; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.