本地eventEmitter听全局eventEmitter [英] Local eventEmitter listening to global eventEmitter

查看:152
本文介绍了本地eventEmitter听全局eventEmitter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎写了问题标题为 - 在eventEmitters之间进行通信

I almost wrote the question title as - Communicating between eventEmitters

我有一个node.js模块(X)全局范围(它使用eventEmitter)。然后我有代码是每个套接字的本地(用户连接)。

I have a node.js module (X) that is on the global scope (it uses eventEmitter). I then have code that is local to each socket (user connected).

现在我通过一个全局变量G = {'X' X},以便套接字可以这样访问X:

right now i am carrying X through the process on a global variable G={'X':X} so that the socket can then access X like this:

G.X.on('someEvent',doSomething);

这是笨蛋!现在每当我启动我的服务器,它似乎行为正常(我收到事件),但是如果我刷新页面并发出一个事件我得到它两次。如果我再次刷新页面,我会收到这个事件3次。

This is dumb! Now every time i start my server it seems to act fine (I receive the event), but then if I refresh the page and emit an event I get it twice. If I refresh the page again I get the event 3 times.

我认为我将监听器绑定到全局的同一eventEmitter。

I think that I am binding the listener to the same eventEmitter that is global.

我如何使一个单独的本地eventListener监听全局eventEmiter的发布?

How can I make a separate local eventListener to listen for the emits of the global eventEmiter?

我知道如何设置eventEmiter :

I know how to set up an eventEmiter:

var events = require('events');
var ee = new events.EventEmitter();

ee.on('someEvent',function(){console.log('hello');});

但它没有捕获另一个的事件...

but it does not catch the event of another...

我也尝试使用eventEmitter复制模块

I have also tried copying the module using the eventEmitter

var ee = G.X;
ee.on('someEvent',function() { console.log('hello'); });

但它仍然会收到一个事件的倍数。

But it still receives multiples of an event.

hello
hello
hello


推荐答案

这个问题在很久以前被问到,但是这里是我的答案,因为没有答案。

This question was asked quite some time ago, but here's my answer anyways, seeing as there's no answer for it yet.

收听套接字对象的关闭事件,然后删除回调到你的全局。所以它看起来像:

Listen to the socket object's "close" event, then remove the callbacks to your global. So it would look like:

X.addListener("someEvent", callback);

X.on("someEvent", function(socket){
  socket.on("close", function(){
    X.removeListener("someEvent", callback);
  });
});

这篇关于本地eventEmitter听全局eventEmitter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆