Skip to content
Advertisement

NodeJS Nested Event listeners

I don’t get it, Why passed argument to the event emitter with nested event listeners streams all values? Is it because it has to pass through the upper level ‘join’ listener? Is variable information stored somewhere?

JavaScript

This creates TCP server. Then you can join with tellnet localhost 7000,

Advertisement

Answer

Please replace channel.on(‘broadcast’,…) with channel.once(‘broadcast’,…). So use ‘once’ subscription which will remove the ‘broadcast’ listener once handled.

For each ‘join’ subscription we had a ‘broadcast’ subscription. Lets say after 3 joins there will be three subscription to ‘broadcast’ event. So when the emitter emits with ‘broadcast’ all three subscription is called. The value of sub is the previous value and only sub2 is updated.

The modified code will look like this. I kind of put some additional console logs for better understanding.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement