user578895
user578895

Reputation:

Does node have a way to consume/stop an event?

I'm looking for a way to add events such that they fire sequentially and optionally pass through. I'm wondering if there is anything like this natively in the Node API, or if not if anyone knows of a decent npm package that accomplishes this:

obj
  .on('event-A', function(){
    // log something()
    // consume or stop the event
  })
  .on('event-A', function(){
    // this never fires
  });

Upvotes: 11

Views: 4014

Answers (2)

user3743222
user3743222

Reputation: 18665

I don't know of any node-api allowing to cancel event dispatching. But you can take any node-compatible event library (node, pubsubjs, etc) and modify the dispatching function with these guidelines:

  • pass a cancel function to your event listener as a this/first/last (pick up the one you like the best) parameter. That cancel function will have a cancel property in a closure, that your event dispatcher will check prior to dispatching events.

But note that:

  • as this is a side-effect, this can make your program a bit harder to reason about. You will have to keep in mind all the places where the side-effect occurs to completely understand you program. Also, your event handlers have to be executed sequentially, which means you must have a consistent definition of order (order of registering listeners, user-defined order?).

Upvotes: 1

user578895
user578895

Reputation:

I just wrote a library (event-chains) that replicates the EventEmitter API and provides cancelation via either rejected promises or by calling this.stop(). Also steals an idea from signals where you can have "single event" emitters.

Upvotes: 1

Related Questions