Say I am creating my own module, which sits on top of the 'net' module. My module has its own events, but also allows clients to listen on network events emitted by the tcp connection:
mymod.on('myevent',...); // my event
mymod.on('connect',...); // net event
mymod.on('end',...); // net event
Right now I'm doing the following
...
tcp.on('connect',function(){ self.emit('connect');});
tcp.on('end',function(){ self.emit('end');});
...
Is there a more idiomatic way from me to simply forward all events (or a subset of events) from one module to clients of another module?
I expect such a scenario comes up all the time, so I'd like to do it the cleanest way I can.
What I've done in the past is handle the newListener
event. I don't bother attaching handlers until one is attached to my class. Then, when it is, I attach it to the base class.
this.on('newListener', function (event, listener) {
baseClassInstance.on(event, listener);
})
You can filter which events are passed through by checking the event
parameter first.
Beware if you have to remove listeners. This may not be the best solution in those cases.
I've never tried it and cannot test this at the moment but you could try the following;
Proxy all events to another object
tcp.emit = mymod.emit.bind(mymod);
Proxy events and call its own;
var oldEmit = tcp.emit;
tcp.emit = function() {
mymod.emit.apply(mymod, arguments);
return oldEmit.apply(this, arguments);
}
Let me know if it works! The above is just a proof of concept and I have put no thought into the side effects of doing this.