Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clean up events assigned from controller?

When, where and how should i get rid of old event listeners when controller is not relevant anymore?

Consider SPA with two routes: /login and /loggedin

app.factory('socket', ['$window', function(window) {
    return window.io();
}]);
app.controller('loginController', ['socket', function (socket) {
    this.tryLogin = function(credentials) {
        socket.emit('login', credentials);
    }
    sokcet.on('loginResponse', function(data) {
        if (data.status == 'OK') {
            // Navigate to loggedInController
        } else {
            // Show error message and keep listening - user might try again
        }
    });
}]);
app.controller('loggedInController', ['socket', function (socket) {/* Logged in, but loginController is still listening for loginResponse */}]);

Problems:

  • When navigating to /loggedin then loginResponse event keeps listening
  • When navigating back to /login page new listener gets added (effectively i have 2 listeners now)
like image 648
Kristian Avatar asked Aug 16 '15 12:08

Kristian


1 Answers

Take a look at Angular's $scope.$on('$destroy') event and use it together with socket.io's removeListener method. Something like this:

app.controller('loginController', ['$scope', 'socket', function ($scope, socket) {
    this.tryLogin = function(credentials) {
        socket.emit('login', credentials);
    }

    socket.on('loginResponse', loginResponse);

    $scope.$on('$destroy', function() {
        socket.removeListener('loginResponse', loginResponse);
    });

    function loginResponse(data) {
        if (data.status == 'OK') {
            // Navigate to loggedInController
        } else {
            // Show error message and keep listening - user might try again
        }
    }
}]);
like image 124
sdgluck Avatar answered Oct 18 '22 02:10

sdgluck