I'm come across a similar problem to Improve this AngularJS factory to use with socket.io but the accepted answer seems to use a function that no longer exists so what would the substitute be for socket.removeAllListeners();
on the client side in an angular.js controller if i need to remove a listener? I'm using socket.io v .9.16
socket.removeAllListeners()
is still there. The reason why it couldn't be called is that the real socket is this one: var socket = io.connect()
.
The "socket" in the following codes is a wrapper that angular factory returns, which only has two methods: on
and emit
.
$scope.$on('$destroy', function (event) {
socket.removeAllListeners();
// or something like
// socket.removeListener(this);
});
What you can do is to add a new getSocket
methods to socket
factory like this:
app.factory('socket', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
// ...
},
emit: function (eventName, data, callback) {
// ...
},
getSocket: function() {
return socket;
}
};
});
Then you can do something like this:
$scope.$on('$destroy', function (event) {
socket.getSocket().removeAllListeners();
// or something like
// socket.getSocket().removeListener(this);
});
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