ai/nanoevents

Suggestion: .once method()

Kelin2025 opened this issue · 5 comments

Hi nano-bro!

I know that nanoevents is positioned as "nano" eventbus but it would be better if .once() method will be implemented.
It's cheaper than writing unbind() for each needed event manually.

I can implement it if you'll agree

ai commented

Hi :).

It is easy to add once by this snippet: 3fe7f74

NanoEvents had a once before, but I found that:

  1. It is a very rare use case
  2. It is easy to make once by on and unbind

Will this snippet useful? We can add nanoevents/once file.

It is a very rare use case

I use nanoevents in my libraries and apps. It's not rare

It is easy to make once by on and unbind

And total app size is larger if we won't move it to upper level :)
But implementing once in application code is not good, it's like implementing debounce or smth else instead of using lodash.

About snippet: usage looks like

once.apply({ emitter }, 'evt', cb)

Maybe:

once (emitter, event, callback) {
  const unbind = emitter.on(event, function () {
    unbind()
    callback.apply(this, arguments)
  })
  return unbind
}

// Usage
once(emitter, 'evt', cb)

?


Also, there's another problem with your implementation: you use this but if you'll pass .on/.emit to external object (as I do in my lib):

const obj = {
  on: bus.on
}

It fails: see this

You can firstly create events instead of this.events (then do this.events = events) and work with events. So there is no need to use .call/.apply, it will always work correctly.

ai commented

This snippet is related to “mix to object” example. I think it is the main use case for a library as NanoEvent.

I made example more clear 3f1ca10

ai commented

@makoven write implementation in JS and export types by index.d.ts