如何清除从控制器分配的事件?
How to clean up events assigned from controller?
When、where 和 how 我应该在控制器时摆脱旧的事件侦听器不再相关了?
考虑 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 */}]);
问题:
- 当导航到
/loggedin
时,loginResponse
事件继续侦听
- 当导航回
/login
页面时 新 监听器被添加(实际上我现在有 2 个监听器)
看看 Angular 的 $scope.$on('$destroy')
event and use it together with socket.io's 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
}
}
}]);
When、where 和 how 我应该在控制器时摆脱旧的事件侦听器不再相关了?
考虑 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 */}]);
问题:
- 当导航到
/loggedin
时,loginResponse
事件继续侦听 - 当导航回
/login
页面时 新 监听器被添加(实际上我现在有 2 个监听器)
看看 Angular 的 $scope.$on('$destroy')
event and use it together with socket.io's 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
}
}
}]);