Skip to content

Instantly share code, notes, and snippets.

@JasonKleban
Last active June 17, 2021 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JasonKleban/924babb9c56d697c2d2a8f6f604eb3d4 to your computer and use it in GitHub Desktop.
Save JasonKleban/924babb9c56d697c2d2a8f6f604eb3d4 to your computer and use it in GitHub Desktop.
A stricter variation of https://gist.github.com/JasonKleban/50cee44960c225ac1993c922563aa540 . This version changes function signatures in the case of `T extends void` to take no data parameter, freeing the non-void case to require its data parameter.
interface ILiteEvent<T> {
on(handler: T extends void
? { (): void }
: { (data: T): void }): void;
off(handler: T extends void
? { (): void }
: { (data: T): void }): void;
}
class LiteEvent<T> implements ILiteEvent<T> {
private handlers: (T extends void
? { (): void }
: { (data: T): void })[] = [];
public on(handler: T extends void
? { (): void }
: { (data: T): void }): void {
this.handlers.push(handler);
}
public off(handler: T extends void
? { (): void }
: { (data: T): void }): void {
this.handlers = this.handlers.filter(h => h !== handler);
}
public trigger: T extends void
? { (): void }
: { (data: T): void } =
((data?: T) => {
this.handlers.slice(0).forEach(h => h(data));
}) as any;
public expose() : ILiteEvent<T> {
return this;
}
}
class Security{
private readonly onLogin = new LiteEvent<string>();
private readonly onLogout = new LiteEvent<void>();
public get LoggedIn() { return this.onLogin.expose(); }
public get LoggedOut() { return this.onLogout.expose(); }
// ... onLogin.trigger('bob');
}
function Init() {
var security = new Security();
var loggedOut = () => { /* ... */ }
security.LoggedIn.on((username) => { /* ... */ });
security.LoggedOut.on(loggedOut);
// ...
security.LoggedOut.off(loggedOut);
}
@JasonKleban
Copy link
Author

Might not be necessary - the simpler version without the optionality on the data parameters seems to work ok with void but microsoft/TypeScript#19259 ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment