admin管理员组

文章数量:1424910

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 acplishes this:

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

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 acplishes this:

obj
  .on('event-A', function(){
    // log something()
    // consume or stop the event
  })
  .on('event-A', function(){
    // this never fires
  });
Share Improve this question edited Apr 13, 2022 at 11:55 Dharman 33.5k27 gold badges101 silver badges149 bronze badges asked Aug 20, 2015 at 11:20 user578895user578895 2
  • Sorry about assuming when I saw the .on. I'm not greatly familiar with node but if there are no inbuilt solutions then, are events frozen or sealed? If not, you could add a cancelled property to check for. Extending this, you should change events.EventEmitter.prototype.on to check for cancelled as well. – Paul S. Commented Aug 20, 2015 at 11:38
  • @PaulS. -- No worries, we all make mistakes :) Unfortunately there isn't an "event" created when you trigger an event, so there's nothing to piggy-back on. It just passes through whatever arguments. e.g. .trigger('a', 'b') will call handler('a', 'b'), not handler(ev, 'a', 'b') or similar. – user578895 Commented Aug 20, 2015 at 11:42
Add a ment  | 

2 Answers 2

Reset to default 1

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.

I don't know of any node-api allowing to cancel event dispatching. But you can take any node-patible 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 pletely 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?).

本文标签: javascriptDoes node have a way to consumestop an eventStack Overflow