scottcorgan / tiny-emitter

A tiny (less than 1k) event emitter library
MIT License
935 stars 67 forks source link

Emit events on next tick #2

Closed xixixao closed 9 years ago

xixixao commented 10 years ago

Is it a design choice to call the listeners immediately?

scottcorgan commented 10 years ago

Yes it was.

I'm not opposed to nextTick. What would be your reason or use cases?

xixixao commented 10 years ago

(setTimeout 1) Well, they are two very distinct behaviors. I quickly tried to search for some good practices, but I'd say it is simply easier to reason about events if they are emitted after the current execution stream has finished.

scottcorgan commented 10 years ago

Let me think about how to handle this. I'll do some research on it.

silverbucket commented 9 years ago

You also don't block the call stack any more then necessary by using setTimeout(func, 0);. It's generally nicer to do this, adding it to the queue to be processed after the call stack has completed.

Consider the case of looping through an array of thousands of records. For every record we need to emit an event. If we are to emit the events immediately then the entire loop will slow down and execute the library logic each time, slowing down the loop considerably.

Alternatively, with a setTimeout the loop will only queue the process and continue through the loop much faster. The events are still emitted near immediately, they just don't block the loop and clog up the call stack.

I'm very much in favor of this behavior as well.

ayamflow commented 9 years ago

Shouldn't that be up to the user to emit on the next frame if needed ? I'm thinking with other use cases in mind when one wants the listeners to trigger right after the event was emitted.

A simple example would be a backbone view with "life cycle events" like beforeRender/render/afterRender when you want each listener to fire before the next hook.

Prinzhorn commented 9 years ago

I'm with @ayamflow here. I trigger an event for every requestAnimationFrame with some custom data and every artificial delay would be undesirable.

scottcorgan commented 9 years ago

All good points. It's been the way it is for quite some time. Going to close in favor of keeping current functionality.

Open for more discussion thought.

silverbucket commented 9 years ago

@scottcorgan what about an optional init-time decision?

var emitter = new Emitter({
  emitOnNextTick: true   // default: false
});
scottcorgan commented 9 years ago

I do think it's an interesting feature, but I think wrapping tiny-emitter with that feature may be a better approach. Keeps it tiny. It's fairly easy to extend the class and overwrite the emit method in a new library.

class TinyEmitterNextTick extends TinyEmitter {
  constructor () {
    super()
  }

  emit (...args) {
    process.nextTick(() => super.emit(...args))
  }
}

let emitter = new TinyEmitterNextTick()

// Use the tiny emitter api as normal