Last active
March 15, 2022 16:51
-
-
Save mindplay-dk/604d8112300b133634b3 to your computer and use it in GitHub Desktop.
Type-safe event hooks 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 Handler<TEvent> = (event: TEvent) => void; | |
interface Hook<TEvent> { | |
(handler: Handler<TEvent>): void; | |
send(event: TEvent): void; | |
} | |
function hook<TEvent>(): Hook<TEvent> { | |
const handlers: Array<Handler<TEvent>> = []; | |
const fn = function (handler: Handler<TEvent>) { | |
handlers.push(handler); | |
}; | |
return Object.assign( | |
fn, | |
{ | |
send(event: TEvent) { | |
for (var i = 0; i < handlers.length; i++) { | |
handlers[i](event); | |
} | |
} | |
} | |
) | |
} | |
// EXAMPLE: | |
interface LoginEvent { | |
username: string; | |
success: boolean; | |
} | |
class UserModel { | |
onLogin = hook<LoginEvent>(); | |
} | |
var model = new UserModel(); | |
// register an event listener: | |
model.onLogin(event => console.log(event)); | |
// send an event: | |
model.onLogin.send({ username: 'Rasmus', success: true }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment