The function signature that listeners must match
Event emitter with register, invoke, invokeAsync, and clear methods
// Create emitter for specific function signature
const onUserLogin = OnFunc<(userId: string, timestamp: Date) => void>();
// Register listeners (returns unregister function)
const unsubscribe1 = onUserLogin((userId, timestamp) => {
console.log(`User ${userId} logged in at ${timestamp}`);
});
const unsubscribe2 = onUserLogin((userId) => {
trackAnalytics('login', userId);
});
// Trigger all listeners
onUserLogin.invoke('user123', new Date());
// Async invocation
await onUserLogin.invokeAsync('user456', new Date());
// Unregister specific listener
unsubscribe1();
// Clear all listeners
onUserLogin.clear();
// Auto-unregister with ONCE (listener runs only once)
const onDataLoad = OnFunc<(data: string) => void>();
onDataLoad((data) => {
console.log(`Data loaded: ${data}`);
return OnFuncReturn.ONCE; // Automatically unregisters after first invocation
});
onDataLoad.invoke('first'); // Logs "Data loaded: first"
onDataLoad.invoke('second'); // No output - listener already removed
// Conditional unregister with UNREGISTER
const onMessage = OnFunc<(msg: string) => void>();
onMessage((msg) => {
console.log(`Received: ${msg}`);
if (msg === 'stop') {
return OnFuncReturn.UNREGISTER; // Unregisters when condition is met
}
});
onMessage.invoke('hello'); // Logs "Received: hello"
onMessage.invoke('world'); // Logs "Received: world"
onMessage.invoke('stop'); // Logs "Received: stop" and unregisters
onMessage.invoke('ignored'); // No output - listener was unregistered
Creates a type-safe event emitter for a specific function signature.
OnFunc provides a simple pub/sub pattern where multiple listeners can be registered for a specific function signature. All listeners are invoked when the event is triggered, with errors caught and ignored. Supports both synchronous and asynchronous invocation.