chrisenytc / ng-socket

Angular Module for Socket.io
MIT License
49 stars 18 forks source link

removeListener on $scope destruction doesn't work #15

Open somelinguist opened 8 years ago

somelinguist commented 8 years ago

This isn't working to automatically remove listeners on $scope destruction:

$socket.on('someEvent', $scope, function(data) { ... });

If you navigate from one page to another and then back to the first, you end up with duplicate listeners.

It looks like it has to do with the way the ng-socket adds the listeners using its angularCallback wrapper. Currently, the call to socket.on() and socket.removeListener() are referencing two instances of the callback instead of the same instance of it, so the call to socket.removeListener() is trying to remove an instance that hasn't been registered.

Assigning the wrapped callback to a variable and then passing the variable to socket.on() and socket.removeListener() works:

function addListener(name, scope, callback) {
        initializeSocket();

        if (arguments.length === 2) {
          scope = null;
          callback = arguments[1];
        }
        var cb = angularCallback(callback);
        socket.on(name, cb);

        if (scope !== null) {
          scope.$on('$destroy', function () {
            removeListener(name, cb);
          });
        }
      }
function removeListener(name, callback) {
        initializeSocket();
        socket.removeListener(name, callback);
      }