在我的一个 Controller 中,有一条指令 <div keypress-events>
订阅按下的键:
directives.directive('keypressEvents', ['$document', '$rootScope', function ($document, $rootScope) {
return {
restrict: 'A',
link: function () {
$document.bind('keydown', function (e) {
$rootScope.$broadcast('keypress', e, e.which);
});
}
}
}]);
还有一个监听器,当用户按下任意箭头键时执行分页。
var listener = $scope.$on('keypress', function (e, a, key) {
$scope.$apply(function () {
$scope.key = key;
if (key == 39) {
$scope.currentPage = Math.min($scope.currentPage + 1, $scope.numPages)
} else if (key == 37) {
$scope.currentPage = Math.max($scope.currentPage - 1, 1)
}
});
})
但是,当您导航到另一个 Controller 然后返回时,监听器将被调用两次。那么我怎样才能取消订阅该事件呢?
我只是尝试销毁监听器,但这不起作用......
$scope.$on('$destroy', function() {
listener(); // remove listener.
});
最佳答案
因为当您重新访问页面时,指令中的 keydown
事件会被限制两次。您可以做的是,在离开页面之前,注意删除
指令的 keydown
事件,与 scope
的 $destroy
事件 Hook 。
代码
directives.directive('keypressEvents', ['$document', '$rootScope', function ($document, $rootScope) {
return {
restrict: 'A',
link: function (scope) {
var event = function (e) {
$rootScope.$broadcast('keypress', e, e.which);
};
$document.on('c', event);
scope.$on('$destroy', function (){
angular.element($document).off('keydown', event);
})
}
}
}]);
Note: As of jQuery 3.0,
.unbind()
has been deprecated. It was superseded by the.off()
method since jQuery 1.7, so its use was already discouraged.
关于javascript - AngularJS:取消订阅事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45390902/