javascripteventssocket.io

Socket.io Client: respond to all events with one handler?


Is it possible to have a socket.io client respond to all events without to have specify each event individually?

For example, something like this (which obviously doesn't work right now):

var socket = io.connect("http://myserver");

socket.on("*", function(){
  // listen to any and all events that are emitted from the
  // socket.io back-end server, and handle them here.

  // is this possible? how can i do this?
});

I want this callback function to be called when any / all events are received by the client-side socket.io code.

Is this possible? How?


Solution

  • It looks like the socket.io library stores these in a dictionary. As such, don't think this would be possible without modifying the source.

    From source:

    EventEmitter.prototype.on = function (name, fn) {
        if (!this.$events) {
          this.$events = {};
        }
    
        if (!this.$events[name]) {
          this.$events[name] = fn;
        } else if (io.util.isArray(this.$events[name])) {
          this.$events[name].push(fn);
        } else {
          this.$events[name] = [this.$events[name], fn];
        }
    
        return this;
      };