web-client-ui icon indicating copy to clipboard operation
web-client-ui copied to clipboard

Add functions for emitting/listening events

Open mofojed opened this issue 1 year ago • 1 comments

Currently when we emit events, we simply call eventHub.emit(eventName, ...), which does not offer any type protection. Similarly, we call eventHub.on(eventName, callback) which does not offer any type protection for the callback.

We should use functions to emit events and listen to them, so we get type protection. PanelEvent.OPEN is being wired up with #2144, we should wire up all the other events as well.

mofojed avatar Jul 16 '24 14:07 mofojed

We also have the option of better typing eventHub.emit. One way to do this is to use a type map of eventName to function args. Something like:

interface EventPayload {
  [key: string]: unknown[];
  ['test']: [number, Date];
  ['blah']: [string];
}

and then can genericize the eventHub

class EventEmitter<T extends Record<string, unknown[]>> {
   ...
   emit<K extends keyof T>(eventName: K, ...args: T[K])
const emitter: EventEmitter<EventPayload> = ...;

// types enforced of event name mapped to proper args
emitter.emit('test', 4, new Date());

bmingles avatar Jul 16 '24 14:07 bmingles