简体   繁体   English

AngularJS:取消订阅事件

[英]AngularJS: Unsubscribe Event

In one of my controllers, there is a directive <div keypress-events> that subscribes to pressed keys: 在我的一个控制器中,有一个指令<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);
            });
        }
    }
}]);

There is also a listener that performs pagination when a users pressed any arrow keys. 当用户按下任意箭头键时,还有一个侦听器执行分页。

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)
        }
    });
})

However, when you navigate to another controller and then go back, the listener will be called twice. 但是,当您导航到另一个控制器然后返回时,侦听器将被调用两次。 So how can I unsubscribe to that event? 那么我该如何退订该事件?

I tried only to destroy the listener, but this does not work... 我只是试图销毁监听器,但这是行不通的...

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

Because keydown event from directive gets bounded twice when you revisit the page. 因为当您重新访问页面时,来自指令的keydown事件被绑定两次。 What you could do is, before moving away from page take care of removing keydown event of directive, for the same place hook on $destroy event of scope . 您可以做的是,在离开页面之前,请注意删除指令的keydown事件,并在scope $destroy事件上使用相同的位置。

Code

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. 注意 :从jQuery 3.0开始,不推荐使用.unbind() It was superseded by the .off() method since jQuery 1.7, so its use was already discouraged. 自jQuery 1.7起,它已由.off()方法取代,因此不鼓励使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM