在node.js中,如何将模块的所有事件转发到另一个 [英] in node.js, how to forward all events of module to another
问题描述
假设我正在创建自己的模块,它位于'net'模块的顶部。我的模块有自己的事件,但也允许客户端监听tcp连接发出的网络事件:
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
现在我正在做以下事情
...
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.
推荐答案
我过去所做的是处理 newListener
事件。我不打扰附加处理程序,直到一个人连接到我的班级。然后,当它是,我将它附加到基类。
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.
这篇关于在node.js中,如何将模块的所有事件转发到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!