Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Persist events that not yet have a handler #161

Open
AndreasJilvero opened this issue May 6, 2022 · 1 comment
Open

Persist events that not yet have a handler #161

AndreasJilvero opened this issue May 6, 2022 · 1 comment

Comments

@AndreasJilvero
Copy link

AndreasJilvero commented May 6, 2022

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.

@phoenix-ru
Copy link

phoenix-ru commented May 17, 2022

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)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants