Last active
June 17, 2021 18:40
-
-
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.
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
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; | |
} | |
} |
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
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Might not be necessary - the simpler version without the optionality on the data parameters seems to work ok with
void
but microsoft/TypeScript#19259 ?