Search code examples
javascriptsocket.ioobserver-pattern

Is socket.io's "on" method an adder or setter?


In socket.io, will using "on" twice replace the older registration or will the event fire both listeners? Is it a generally consistent behavior with javascript "on" methods in general? And is there a reason there is no socket.io documentation for this?

var socket = io.connect("host:port")
socket.on('data', function(data) {
  console.log('listener1');
}

socket.on('data', function(data) {
  console.log('listener2');
}

Solution

  • JavaScript has no on method. Libraries just implement this as part of an Event Emitter/Pub-Sub pattern, where code "listens" from other code.

    And no, it will not replace the existing registrations. They get added into a "queue". Think of it as this: It's not only one piece of code that listens for data to arrive. There could be hundreds of lines listening for that same data.