简体   繁体   English

在Node.js中的事件处理程序之前调用事件发射器

[英]Calling the event emitter before the event handler in nodejs

I am going through this code and I have seen the nodejs event emitter being called before the event handler was defined( this line and this line ). 我正在看这段代码 ,我已经看到在定义事件处理程序之前( 此行此行 )调用了nodejs事件发射器。

When I try to replicate the same, no event gets handled. 当我尝试复制相同内容时,不会处理任何事件。

    eventEmitter.emit('event');

    eventEmitter.on('event', () => {
        console.log('event handled');
    });

When you put the event emitter after the event handler ' event handled ' gets logged. 当您将事件发射器放置在事件处理程序“ 事件已处理 ”之后时,将其记录下来。

Is the code on GitHub wrong? GitHub上的代码是否错误? Or does it still work because it is in a module and there is a way the module is imported that allows it to work? 还是因为它在模块中并且通过某种导入模块的方式允许它工作而仍然起作用? Kindly explain. 请解释。 Thank you. 谢谢。

The event emission on line 44 is inside of the handler being bound to the ioChat's "connection" event which is not invoked before the binding of eventEmitter's "get-all-users" event on line 181. So even though the line where the event is invoked comes first, it will not be invoked first. 第44行的事件发出位于绑定到ioChat的“连接”事件的处理程序内部,该事件在绑定第181行的eventEmitter的“ get-all-users”事件之前不会被调用。因此,即使该事件所在的行被调用首先发生,不会被首先调用。

Example: 例:

eventEmitter.on('connection', () => {
  console.log('this should log second');
  eventEmitter.emit('someEvent');
});

eventEmitter.on('someEvent', () => {
  console.log('this should log third');
});

console.log('this should log first');
eventEmitter.emit('connection');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM