我想自定义Node EventEmitter以实现三件事:1)让我知道事件是否已发出但没有任何侦听器,2)使用我自己的调试模块自动记录该事件(而无需修补或插入任何事件)其他代码),以及3)传递一个标识符,这样我就知道此日志事件来自哪个EventEmitter。结合这里的所有内容,这就是我想出的,我想知道是否有人对改进有更好的建议或更好的方法:
const debugger = new SuperDuperDebugger();
const nodeEventEmitter = require('events').EventEmitter;
class EventEmitter extends nodeEventEmitter {
constructor() {
super();
}
emit() {
let debugId = this.debugId + " " || '';
let eventName = arguments[0];
if (!super.listenerCount(eventName)) {
debugger.error(debugId + eventName + " event emitted without listener(s)");
return false;
}
super.emit.apply(this, arguments);
}
}
const usbEvents = new EventEmitter();
usbEvents.debugId = 'USB';
const bluetoothEvents = new EventEmitter();
bluetoothEvents.debugId = 'Bluetooth';
const otherEvents = new EventEmitter();
// example usage
usbEvents.emit('foo');
bluetoothEvents.emit('bar');
otherEvents.emit('baz');
debugger.output();
// output
ERROR: USB foo event called without listener(s)
ERROR: Bluetooth bar event called without listener(s)
ERROR: baz event called without listener(s)