Reputation: 7686
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).
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? 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.
Upvotes: 0
Views: 928
Reputation: 392
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.
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');
Upvotes: 2