Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to use instead of socket.removeAllListeners(); on the client side

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

like image 304
Austin Davis Avatar asked Mar 22 '23 01:03

Austin Davis


1 Answers

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);
});
like image 174
Daiwei Avatar answered Apr 25 '23 06:04

Daiwei