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

前端 未结 14 1935
时光取名叫无心
时光取名叫无心 2020-11-28 04:16

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 do

14条回答
  •  难免孤独
    2020-11-28 04:41

    Here you go ...

    var socket = io.connect();
    var globalEvent = "*";
    socket.$emit = function (name) {
        if(!this.$events) return false;
        for(var i=0;i<2;++i){
            if(i==0 && name==globalEvent) continue;
            var args = Array.prototype.slice.call(arguments, 1-i);
            var handler = this.$events[i==0?name:globalEvent];
            if(!handler) handler = [];
            if ('function' == typeof handler) handler.apply(this, args);
            else if (io.util.isArray(handler)) {
                var listeners = handler.slice();
                for (var i=0, l=listeners.length; i
                                                            
提交回复
热议问题