btford / angular-socket-io

Socket.IO component for AngularJS
1.51k stars 233 forks source link

socket.removeListener not working #152

Open swapnil001 opened 7 years ago

swapnil001 commented 7 years ago

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?

melliott03 commented 7 years ago

I'm experiencing the same issue. Did you find a solution?

swapnil001 commented 7 years ago

No. It did not work. I had to change my system to work with removeAllListener property and on controller exit remove all listeners.

melliott03 commented 7 years ago

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.

melliott03 commented 7 years ago

1) include the cdn in your html

2) 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);
      };
    },

  };
}]);

3) Inject the factory into your controller 4) instead of socket.removeListener, use socket.off(eventName) 5) uninstall angular-socket-io