I have 2 classes: EventEmitter and EventCatcher. The EventCatcher has 2 members of EventEmitter. EventEmitter emits a test event. In the catcher I want to catch all test events and do something:
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();
};
Is there a way to attach X events to the EventCatcher class in attachHandler, without having to manually attach for each EventEmitter class?
Something like this?
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();
});
};
This written is from mind, so I don't really know if the scope is correct inside the callback.