ngSocketIO
ngSocketIO copied to clipboard
Added disconnect method to the directive
Hi,
Added a disconnect method because I noticed that in my Angular app when I have a controller that uses a socket, upon navigating to a different route, the socket is still alive and well on the controller (that should have been destroyed?).
Hence I added a disconnect method to the socket that I can call on the destroy event of my controller to disconnect the socket properly.
Test for the disconnect included. Cheers!
Hi @Hcu. Sorry for the very late response. :(
Currently a connection is established once, and only once, when the socket
factory is instantiated by Angular. I guess if you disconnects the socket you will be no longer able to use it.
Makes sense?
Yes, the behavior I had experienced was that if I had a socket open on a controller, and I navigated to a route in my angular app which uses a different controller, then the original controller (the one with the socket connection) would continue to live and hence the socket would still receive updates. So for example, you have a chat window at yoururl/chat and decide to use a socket for communication, then you navigate to yoururl/lobby, what I noticed is that my controller for yoururl/chat would still receive socket updates while I already left the chat and am in the /lobby. For some reason the controller at yoururl/chat would still live on while I am on yoururl/lobby.
Therefor I added a disconnect method so I can call that when I navigate to the new route / controller (one that doesn't need the socket). So yes, I want the socket to be disconnected when I navigate to a different route / controller in my app and that's what I use the disconnect method for, to explicitly close it when I need it to be closed.
Cheers
Wouldn't it be simpler to just remove the listeners when the controller's scope is destroyed instead of disconnecting the socket altogether? That's easy to do by using the bindTo
method:
socket.on('someEvent', function(data) {
...
}).bindTo($scope);
My concern about a disconnect
method is because the socket
service is a singleton, as all Angular services, and if it gets disconnected it'll be disconnected for the entire app. Using your chat application example, if the lobby page needed to show a real time list of the connected users I think it would require the socket to be connected.
What do you think?
What if we could have a method 'bindOnlyTo'' similar to 'bindTo' . Difference is whenever scope destroyed it 'll disconnect and whenever this method called for scope , then only it will initiate connection.
For disconnect add , at the end of line 90 and after add these line:
disconnect: function(){
if(socket){
socket.io.disconnect();
}
},