When using SocketIO, receiving any message is done as so:
socket.on("eventname", function() {
// Whatever
}
But "eventname" can be literally any string of text.
How did they achieve that? How do they have an event listener for each and every possible string? Do they add event listeners AS the messages come in?
I've tried reading the SocketIO source code, but it went right over my head.
The answer can be found looking at the documentation:
From the source code of Socket.IO:
socket.on(eventName, callback)
(inherited from EventEmitter)
From here:
Internally, the EventEmitter keeps track of an object called this.events that maps event names to arrays of event handlers. When a program calls the on method with an event name and event handler, the EventEmitter adds the handler to the array for that event name.
So basically, the socket keeps a map of events, keyed by name, to an array of functions that are called when that event is received.
And if you look at the documentation of EventEmitter.on, you'll see that it is pretty dumb - it does not check that you aren't adding the same function twice:
.on() -> Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.