Starting with Node.js v6.0.0, the new class syntax and the argument distribution operator are fully supported, therefore it is quite safe and fairly easy to implement the desired functionality using simple inheritance and method overrides:
'use strict'; var EventEmitter = require('events'); class MyEmitter extends EventEmitter { emit(type, ...args) { super.emit('*', ...args); return super.emit(type, ...args) || super.emit('', ...args); } }
This implementation is based on the fact that the original emit method returns true / false depending on whether the event was processed by some listener or not. Note that overriding includes a return , so we save this behavior for other consumers.
The idea here is to use the star event ( * ) to create handlers that run for each individual event (say, for logging purposes) and an empty event ( '' ) for the default value or to intercept the entire handler that runs if nothing happens. still catches this event.
We always call the star ( * ) event first, because in the case of error events without any handlers, the result is actually an exception. EventEmitter implementation for more details.
For example:
var emitter = new MyEmitter(); emitter.on('foo', () => console.log('foo event triggered')); emitter.on('*', () => console.log('star event triggered')); emitter.on('', () => console.log('catch all event triggered')); emitter.emit('foo'); // Prints: // star event triggered // foo event triggered emitter.emit('bar'); // Prints: // star event triggered // catch all event triggered
Finally, if an EventEmitter instance already exists, but you want to configure this particular instance for a new behavior, this can easily be done by correcting the method at run time as follows:
emitter.emit = MyEmitter.prototype.emit;
Victor Schröder Jan 30 '19 at 1:04 2019-01-30 01:04
source share