socket.removeListener not working
Hi,
I am trying to remove one listener when my controller is changing via
$scope.$on('$destroy', function() {
hpSocketFactory.removeListener(emiterListernerLeagueLobby, function(err) {
});
hpSDSocketFactory.removeListener(emiterListernerMatchID, function(err) {
});
});
But it does not seem to work. Listener is not removed. How to remove one particular listener when controller is changing?
I'm experiencing the same issue. Did you find a solution?
No. It did not work. I had to change my system to work with removeAllListener property and on controller exit remove all listeners.
I came up with the following solution to make removeListener work if you're interested. If involves not angular-socket-io and writing a factory to export socket.io. I think it's easier and more straightforward and it works.
- include the cdn in your html
- Create a factory
myApp.factory('Socket', ['$rootScope', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
function wrapper() {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
}
socket.on(eventName, wrapper);
return function () {
socket.removeListener(eventName, wrapper);
};
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if(callback) {
callback.apply(socket, args);
}
});
});
},
off: function (eventName) {
function wrapper() {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
}
socket.off(eventName);
return function () {
socket.removeListener(eventName, wrapper);
};
},
removeAllListeners: function (eventName) {
socket.removeAllListeners(eventName);
return function () {
socket.removeAllListeners(eventName);
};
},
addListener: function (eventName, callback) {
function wrapper() {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
}
socket.on(eventName, wrapper);
return function () {
socket.on(eventName, wrapper);
};
},
};
}]);
- Inject the factory into your controller
- instead of socket.removeListener, use socket.off(eventName)
- uninstall angular-socket-io