How to clear events assigned by the controller?

When , where and how to get rid of old event listeners when the controller is no longer suitable?

Consider a 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 switching to /loggedin event continues to be listened
  • When you go back to the /login page, a new listener (in fact, I now have 2 listeners)
+6
source share
1 answer

Take a look at the Angular $scope.$on('$destroy') event and use it along with socket.io removeListener . Something like that:

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

All Articles