Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Last active March 15, 2022 16:51
Show Gist options
  • Save mindplay-dk/604d8112300b133634b3 to your computer and use it in GitHub Desktop.
Save mindplay-dk/604d8112300b133634b3 to your computer and use it in GitHub Desktop.
Type-safe event hooks in Typescript
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