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:
/loggedin
then loginResponse
event keeps listening/login
page new listener gets added (effectively i have 2 listeners now)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
}
}
}]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With