Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in node.js, how to forward all events of module to another

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.

like image 416
Shahbaz Avatar asked Sep 23 '12 23:09

Shahbaz


1 Answers

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.

like image 87
Brad Avatar answered Oct 13 '22 12:10

Brad