附加一个事件监听器到一个类来监听来自其成员的事件

我有2个类:EventEmitter和EventCatcher。 EventCatcher有2个EventEmitter成员。 EventEmitter发出一个testing事件。 在捕手,我想抓住所有的testing事件,并做一些事情:

EventEmitter

var events = require('events'); var sys = require('util'); module.exports = eventEmit; function eventEmit(name) { this.name = name; events.EventEmitter.call(this); } sys.inherits(eventEmit, events.EventEmitter); eventEmit.prototype.emitTest = function() { var self = this; self.emit('test'); } 

EventCatcher

 var eventEmit = require('./eventEmit'); module.exports = eventCatch; function eventCatch() { this.eventEmitA = new eventEmit("a"); this.eventEmitB = new eventEmit("b"); this.attachHandler(); } eventCatch.prototype.attachHandler = function() { //I want to do something like: // this.on('test', function() }; this.eventEmitA.on('test', function() { console.log("Event thrown from:\n" + this.name); }); this.eventEmitB.on('test', function() { console.log("Event thrown from:\n" + this.name); }); }; eventCatch.prototype.throwEvents = function() { var self = this; self.eventEmitA.emitTest(); self.eventEmitB.emitTest(); }; 

有没有办法将X事件附加到attachHandler的EventCatcher类,而不必手动附加每个EventEmitter类?

像这样的东西?

 var eventEmit = require('./eventEmit'); module.exports = eventCatch; function eventCatch() { this.emitters = []; this.emitters.push(new eventEmit("a")); this.emitters.push(new eventEmit("b")); this.on('test', function() { console.log("Event thrown from:\n" + this.name); }); } eventCatch.prototype.on = function(eventName, cb) { this.emitters.forEach(function(emitter) { emitter.on(eventName, cb); }); }; eventCatch.prototype.throwEvents = function() { this.emitters.forEach(function(emitter) { emitter.emitTest(); }); }; 

这写的是从头脑,所以我真的不知道范围内的callback是否正确。