Bijou Trouvaille Bijou Trouvaille - 1 year ago 283
Javascript Question

How to unsubscribe from a 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:'news', obj.socketEvent)

before the object is deleted, but alas, there isn't an
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;

Answer Source

From looking at the source of (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);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download