Last active
August 21, 2019 13:43
-
-
Save mrbalihai/8c9259ee961b59e24171015537c98e20 to your computer and use it in GitHub Desktop.
A basic event bus in 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
type SubscriptionFn = (data: object) => void | |
interface EventSubscription { | |
event: GameEvent; | |
fn: SubscriptionFn; | |
} | |
export enum GameEvent { | |
MouseClick | |
} | |
export namespace EventBus { | |
const subscriptions = new Map<symbol, EventSubscription>(); | |
export function subscribe(event: GameEvent, fn: SubscriptionFn): symbol { | |
const id = Symbol(); | |
subscriptions.set(id,{ event, fn }); | |
return id; | |
} | |
export function unsubscribe(id: symbol) { | |
subscriptions.delete(id) | |
} | |
export function publish(event: GameEvent, data: any) { | |
[...subscriptions.values()] | |
.filter((e: EventSubscription) => e.event === event) | |
.forEach((e) => e.fn(data)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment