gpt4 book ai didi

javascript - AngularJS:取消订阅事件

转载 作者:行者123 更新时间:2023-12-01 03:18:16 24 4
gpt4 key购买 nike

在我的一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com