代码之家  ›  专栏  ›  技术社区  ›  Pascal

AngularJS:取消订阅事件

  •  0
  • Pascal  · 技术社区  · 9 年前

    <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.
    });  
    
    1 回复  |  直到 9 年前
        1
  •  2
  •   Pankaj Parkar    9 年前

    keydown 当您重新访问页面时,指令中的事件会两次绑定。您可以做的是,在离开页面之前,注意删除 键盘按下 指令事件,用于同一位置挂钩 $destroy 事件 scope

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

    笔记 :从jQuery 3.0开始, .unbind() .off() 方法,因此它的使用是

    推荐文章