Persist events that not yet have a handler
There's a risk that a event is emitted before its' handler has been registered. You might say that such code is bad design, but I'd like to be lazy ;) Also, given that code splitting is being more and more adopted, I think this scenario is very real.
Would it be possible to persist events that don't have a handler (yet)? Whenever .on(...) is run, mitt would then check the persisted events in order to find unprocessed ones, and then handle those events immediately.
I think the footprint for this change can be quite small, but I can't speak for performance. Maybe we can opt-in to the behaviour.
I think you can emulate it with a simple queue and a catch-all, something like
const queue = new Map<string, unknown>()
emitter.on('*', (type: string, ev: unknown) => {
// Disable processing when event is already registered
if (emitter.all.has(type)) return
if (!queue.has(type)) queue.set(type, [])
queue.get(type).push(ev)
})
And then, when you are finally ready, add the necessary handler and flush the queue:
function addHandler(type: string, handler: (v: unknown) => void) {
emitter.on(type, handler)
;(queue.get(type) || []).forEach(v => emitter.emit(type, v))
// Free the resources
queue.delete(type)
}