Search code examples
javascriptsocket.iopublish-subscribe

How to unsubscribe from a socket.io subscription?


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

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

These objects have a short life span and are frequently created, generating many subscriptions. This seems like a memory leak and an error prone situation which would intuitively be prevented this way:

socket.off('news', obj.socketEvent)

before the object is deleted, but alas, there isn't an off method in the socket. Is there another method meant for this?

Edit: having found no answer I'm assigning a blank method to overwrite the wrapper method for the original event handler, an example follows.

var _blank = function(){};

var cbProxy = function(){
    obj.socketEvent.apply(obj, arguments)
};
var cbProxyProxy = function(){
    cbProxy.apply ({}, arguments)
}
socket.on('news', cbProxyProxy);

// ...and to unsubscribe 
cbProxy = _blank;

Solution

  • From looking at the source of socket.io.js (couldn't find it in documentation anywhere), I found these two functions:

    removeListener = function(name, fn)
    removeAllListeners = function(name)
    

    I used removeAllListeners successfully in my app; you should be able to choose from these:

    socket.removeListener("news", cbProxy);
    socket.removeAllListeners("news");
    

    Also, I don't think your solution of cbProxy = _blank would actually work; that would only affect the cbProxy variable, not any actual socket.io event.