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;
click(function(){ socket. disconnect(); });
Even in terms of network traffic, Socket.IO is way more expensive. In fact, with plain WebSockets, the browser may need to run just two requests: The GET request for the HTML page. The UPGRADE connection to WebSocket.
Conclusion. I think Socket.io is a very useful piece of technology and is incredibly relevant today in spite of the popular view that widespread support for WebSockets makes it redundant. I would recommend that it be used for highly interactive applications. Its namespacing in particular is its strongest point.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With