'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?
var events = require('events');
var net = require('net');
var channel = new events.EventEmitter();
var i = 0;
var subscriptions;
// IF we have two connections
channel.on('join', function(subs) { // Upper Listener
console.log(subs); // -> output 0 when first client joined and 1 for second
channel.on('broadcast', function(subs2) { // lower listener
console.log(subs); // Stream of all connections: -> 0 and 1 ???
console.log(subs2); // Outputs last connection -> 1
});
});
var server = net.createServer(function(client) {
subscriptions = i++; // variable to pass
channel.emit('join', subscriptions); // pass the same variable
client.on('data', function(data) {
channel.emit('broadcast', subscriptions); // pass the same variable
});
});
server.listen(7000);
This creates TCP server. Then you can join with tellnet localhost 7000,
Solution 1:[1]
One reason you might consider separating the join and data events is to do different things during each. For example, in this gist (https://gist.github.com/nicholascloud/603ae8ead6769ad9b8b5), I track clients when they join, and then use the data handler to broadcast a message to all clients EXCEPT the sender. Like so: https://i.imgur.com/pIDy3JD.png
This could be accomplished in many ways, so don't worry about the specific implementation.
Also note that my channel subscriptions are not nested. As long as they are both made prior to the server connecting, my channel should receive all triggered events.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nicholas Cloud |
