Created
January 15, 2019 06:12
-
-
Save ashleydavis/ee0ef4d216f5b4fc9a6bc7c72197e9c4 to your computer and use it in GitHub Desktop.
C# style events in JavaScript
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
// https://stackoverflow.com/a/15964759/25868 | |
export type BasicEventHandler = () => void; | |
export type SenderEventHandler<SenderT> = (sender: SenderT) => void; | |
// | |
// Simulate C# style events in JS. | |
// | |
export interface IEventSource<HandlerType extends Function> { | |
// | |
// Attach a handler for this event. | |
// | |
attach(handler: HandlerType): void; | |
// | |
// Detach a handler for this event. | |
// | |
detach(handler: HandlerType): void; | |
// | |
// Raise the event. | |
// | |
/*async*/ raise(...args: any[]): Promise<void>; | |
}; | |
// | |
// Simulate C# style events in JS. | |
// | |
export class EventSource<HandlerType extends Function> implements IEventSource<HandlerType> { | |
// | |
// Registered handlers for the event. | |
// | |
private handlers: Set<HandlerType> = new Set<HandlerType>(); | |
// | |
// Attach a handler for this event. | |
// | |
attach(handler: HandlerType): void { | |
this.handlers.add(handler); | |
} | |
// | |
// Detach a handler for this event. | |
// | |
detach(handler: HandlerType): void { | |
this.handlers.delete(handler); | |
} | |
// | |
// Raise the event. | |
// | |
async raise(...args: any[]): Promise<void> { | |
for (const handler of this.handlers) { | |
await handler.apply(null, args); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment