Last active
January 26, 2023 06:33
-
-
Save JasonKleban/50cee44960c225ac1993c922563aa540 to your computer and use it in GitHub Desktop.
TypeScript LiteEvent Events implementation
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
interface ILiteEvent<T> { | |
on(handler: { (data?: T): void }) : void; | |
off(handler: { (data?: T): void }) : void; | |
} | |
class LiteEvent<T> implements ILiteEvent<T> { | |
private handlers: { (data?: T): void; }[] = []; | |
public on(handler: { (data?: T): void }) : void { | |
this.handlers.push(handler); | |
} | |
public off(handler: { (data?: T): void }) : void { | |
this.handlers = this.handlers.filter(h => h !== handler); | |
} | |
public trigger(data?: T) { | |
this.handlers.slice(0).forEach(h => h(data)); | |
} | |
public expose() : ILiteEvent<T> { | |
return this; | |
} | |
} |
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 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); | |
} |
@maucaro in case one of the earlier handlers modifies the handlers array in the handling of a particular event. It's just the saner general approach, but I guess you can adjust this for your situation.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was super helpful Jason, thank you! I do have one question: why do you use this.handlers.slice(0).forEach instead of just this.handlers.forEach?