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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With