Last active
January 6, 2017 08:50
-
-
Save vdsabev/5d17e2c218b1625571540e7f48c7eca2 to your computer and use it in GitHub Desktop.
This file contains 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 EventBus { | |
private handlers: Record<string, ((...args: any[]) => void)[]> = {}; | |
trigger(eventName: string, ...args: any[]) { | |
if (this.handlers[eventName]) { | |
this.handlers[eventName].forEach((handler) => handler(...args)); | |
} | |
} | |
on(eventName: string, handler: (...args: any[]) => void) { | |
if (!this.handlers[eventName]) { | |
this.handlers[eventName] = []; | |
} | |
this.handlers[eventName].push(handler); | |
} | |
once(eventName: string, handler: (...args: any[]) => void) { | |
if (!this.handlers[eventName]) { | |
this.handlers[eventName] = []; | |
} | |
const oneTimeHandler = () => { | |
handler.apply(this, arguments); | |
this.off(eventName, oneTimeHandler); | |
}; | |
this.handlers[eventName].push(oneTimeHandler); | |
} | |
off(eventName: string, handler?: (...args: any[]) => void) { | |
if (!this.handlers[eventName]) return; | |
if (!handler) { | |
delete this.handlers[eventName]; | |
} | |
const indexOfHandler = this.handlers[eventName].indexOf(handler); | |
if (indexOfHandler !== -1) { | |
this.handlers[eventName].splice(indexOfHandler, 1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment