如何清理控制器分配的事件?

时间:2022-08-29 22:19:10

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

考虑SPA有两条路线:/ login和/ 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
  • 导航到/ loggedin时,loginResponse事件会继续监听

  • When navigating back to /login page new listener gets added (effectively i have 2 listeners now)
  • 当导航回/登录页面时,新的监听器被添加(实际上我现在有2个监听器)

1 个解决方案

#1


5  

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

看一下Angular的$ scope。$ on('$ destroy')事件,并将它与socket.io的removeListener方法一起使用。像这样的东西:

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
        }
    }
}]);

#1


5  

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

看一下Angular的$ scope。$ on('$ destroy')事件,并将它与socket.io的removeListener方法一起使用。像这样的东西:

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
        }
    }
}]);