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

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


Updated solution for socket.io-client 1.3.7

var onevent = socket.onevent;socket.onevent = function (packet) {    var args = packet.data || [];    onevent.call (this, packet);    // original call    packet.data = ["*"].concat(args);    onevent.call(this, packet);      // additional call to catch-all};

Use like this:

socket.on("*",function(event,data) {    console.log(event);    console.log(data);});

None of the answers worked for me, though the one of Mathias Hopf and Maros Pixel came close, this is my adjusted version.

NOTE: this only catches custom events, not connect/disconnect etc


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;  };


Finally, there is a module called socket.io-wildcard which allows using wildcards on client and server side

var io         = require('socket.io')();var middleware = require('socketio-wildcard')();io.use(middleware);io.on('connection', function(socket) {  socket.on('*', function(){ /* … */ });});io.listen(8000);