我有两个班级:EventEmitter
和EventCatcher
。有EventCatcher
2 个成员EventEmitter
。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');
}
事件捕捉器
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 事件附加到 中的EventCatcher
类attachHandler
,而不必为每个EventEmitter
类手动附加?