最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - socket.io client: how to determine if a handler is already installed - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Dec 12, 2015 at 11:27 robertklep 204k37 gold badges415 silver badges406 bronze badges asked Dec 12, 2015 at 10:50 SPlattenSPlatten 5,76413 gold badges75 silver badges139 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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!

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

发布评论

评论列表(0)

  1. 暂无评论