event-hook

1.0.3 • Public • Published

event-hook

This library provides a mechanism to intercept and perform intermediate processing and mutation on an object's events before they're dispatched out to the object's listeners. For an example or two of how this might be used please see my framed-tcp module on npm or github.

Usage

The module exports two functions that can be used to perform the event management, let's begin with the EventShim function. Simply pass in an object which is an EventEmitter and it will return a 'shim' object. This object should be used to bind event listeners to instead of the original object, in the usual style of shim.on('eventname', function(...){...}). Events that are emitted on the original object will then be dispatched to listeners on the shim object. The shim object has a method addEventProcessor(event, processorFunc) which inserts an intermediate processing function between the object and the shim for that particular event type. The processor will receive a callback function as it's first argument, and subsequent arguments will be the same as the ones passed to emit (excluding the event name). The processor function may do whatever it likes in the meantime, but should execute the callback function to propagate the event out to the shim's listeners. The callback may be executed multiple times if desired, and each call will result in a separate event being emitted on the shim. The callback may be executed with no arguments meaning that the event arguments will be passed on unmodified, or it may be executed by passing one or more arguments which will replace the event arguments. Multiple processors may be registered and they will be executed in the order they are registered. If a previous event modifies the argument list, prevents propagation of the event, or causes multiple events to be emitted then subsequent processors in the chain will see these effects as well as the listeners.

The EventHook function extends that of EventShim but takes it a step further, replacing the EventEmitter-related functions on the object with those of the shim (except for emit). The result of this is that when listeners are attached to the object they will behave as if they were attached to the shim, that is to say the events will have been processed, and possibly modified/suppressed/duplicated along the way. This will not affect any existing listeners attached to the object.

Readme

Keywords

none

Package Sidebar

Install

npm i event-hook

Weekly Downloads

0

Version

1.0.3

License

BSD-3-Clause

Last publish

Collaborators

  • stewartatkins