How to unsubscribe from a socket.io subscription?

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.


If you want to create listeners that "listens" only once use socket.once('news',func). Socket.io automatically will distroy the listener after the event happened - it's called "volatile listener".


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