AngularJS: 取消订阅事件

AngularJS: Unsubscribe Event

在我的一个控制器中,有一个指令 <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)
        }
    });
})

但是,当您导航到另一个控制器然后返回时,侦听器将被调用两次。那么如何取消订阅该活动?

我只尝试破坏监听器,但这不起作用...

$scope.$on('$destroy', function() {
  listener(); // remove listener.
});  

因为 keydown 当您重新访问该页面时,来自指令的事件会被限制两次。您可以做的是,在离开页面之前注意删除 keydown 指令事件,用于 scope.

$destroy 事件上的相同位置挂钩

代码

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.