How to unsubscribe from a socket.io subscription?

前端 未结 11 1330
长发绾君心
长发绾君心 2020-11-30 02:00

Suppose there are objects making subscriptions to a socket server like so:

socket.on(\'news\', obj.socketEvent)

These objects have a short life

11条回答
  •  天命终不由人
    2020-11-30 02:20

    Looking at the code of current version of Socket.io Client (1.4.8) it seems that off, removeAllListeners, removeEventListener are all pointing to the same function.

    Calling any of those, providing event name and/or callback, gives the desired result. Not providing anything at all seems to reset everything.

    Please do be cautious about the fn/callback argument. It has to be the same instance used in the code.

    Example:

    var eventCallback = function(data) {
      // do something nice
    };
    socket.off('eventName', eventCallback);
    

    Would work as expected.

    Example (will also work):

    function eventCallback(data) {
      // do something nice
    }
    socket.off('eventName', eventCallback);
    

    Please be cautious that the callback you are trying to remove is the one that you passed in (this one can bring a lot of confusion and frustration). This example implements a wrapper around initial callback, trying to remove that would not work as the real callback being added is an undisclosed closure instance: http://www.html5rocks.com/en/tutorials/frameworks/angular-websockets/

    Here is the link to that specific line in the codebase: https://github.com/socketio/socket.io-client/blob/master/socket.io.js#L1597

提交回复
热议问题