Prevent $rootScope.$on from calling function several times

风格不统一 提交于 2020-01-01 12:33:14

问题


I have a $rootScope.$on code on top of a controller. I noticed that everytime I load/call this controller, the $rootScope.$on listener increases meaning it will add and add and add a listener, indefinitely as you visit the controller.

I noticed it when I called it via $rootScope.$emit from another controller, the function inside the $rootScope.$on got executed several times even if it was only a single emit/broadcast.

$rootScope.$on('listen', function() {
    $scope.displayString();
});

$scope.displayString = function() {
    console.log('test'); // This display 7 times because I visit the controller 7 times
}

Is it possible to prevent it from creating another listener instance so that when there is already a listener, it won't create a new one.


回答1:


You need to deregister the event listener when you controller's scope is destroyed.

The $on function returns a deregistration function that will remove the listener when the function is invoked.

So you can set it up like this:

var deregister = $rootScope.$on('listen', function() {
    $scope.displayString();
});
$scope.$on('$destroy', deregister);

Note: this will only work if the controller's scope is actually destroyed (e.g. in a directive that is removed from the DOM or when you navigate to a different route). If that doesn't happen then you will need to work out a way of only registering the event listener once.



来源:https://stackoverflow.com/questions/30521559/prevent-rootscope-on-from-calling-function-several-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!