I want to use socket.io in AngularJS. I found the following factory:
app.factory(\'socket\', function ($rootScope) {
var socket = io.connect();
retur
I solved this problem by checking whether listener already exists. If you have multiple controllers that are all loaded at the same time (think of different page modules that all utilize socketIO), removing all registered listeners on $destroy would break the functionality of both the destroyed controller and all the controllers that are still loaded.
app.factory("SocketIoFactory", function ($rootScope) {
var socket = null;
var nodePath = "http://localhost:12345/";
function listenerExists(eventName) {
return socket.hasOwnProperty("$events") && socket.$events.hasOwnProperty(eventName);
}
return {
connect: function () {
socket = io.connect(nodePath);
},
connected: function () {
return socket != null;
},
on: function (eventName, callback) {
if (!listenerExists(eventName)) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
}
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
});
This could be further improved by tracking which listeners were registered by which controller and removing only listeners that belong to destroyed controllers to clean up the memory.