5

What happens if you call the 'on' method multiple times for the same function on a socket? Does calling it multiple times simply overright the last registered function or does it use more resources?

If it is the later, then how do you determine if a handler is already registered?

robertklep
  • 198,204
  • 35
  • 394
  • 381
SPlatten
  • 5,334
  • 11
  • 57
  • 128

2 Answers2

7

I just looked at the socket in Firebug, there is a member called '_callbacks'.

It contains all the registered callbacks, so detecting if one is already registered is as simple as:

    if ( socket._callbacks[strHandlerName] == undefined ) {
    //Handler not present, install now
        socket.on(strHandlerName, function () { ... } );
    }

Thats it!

SPlatten
  • 5,334
  • 11
  • 57
  • 128
  • 2
    For me (using socket.io-client/engine.io-client on node.js), the handler names all have $ in front. ie. `socket._callbacks["$" + strHandlerName]` – kryo Mar 05 '17 at 18:06
1

I am used to work with it this way.

    var baseSocketOn = socket.on;

    socket.on = function() {
        var ignoreEvents = ['connect'] //maybe need it

        if (socket._callbacks !== undefined &&
            typeof socket._callbacks[arguments[0]] !== 'undefined' &&
            ignoreEvents.indexOf(arguments[0]) === -1) {
               return;
        }
        return baseSocketOn.apply(this, arguments)
    };

This is best practice

xorxor
  • 41
  • 4