Prevent $ rootScope. $ From the call function multiple times.

I have $ rootScope. $ in code on top of the controller. I noticed that every time I load / call this controller, $ rootScope. $ On listener is incremented, which means adding and adding and adding a listener indefinitely when visiting the controller.

I noticed this when I called it through $ rootScope. $ emit from another controller, function inside $ rootScope. $ was executed multiple times, even if it was only one source / 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 another instance of the listener from being created so that if there is already a listener it won't create a new one.

+3


source to share


1 answer


You need to unregister the event listener when the control scope is destroyed.

The function $on

returns a deregistration function that removes the listener when the function is called.

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 scope of the controller is actually destroyed (for example, in a directive removed from the DOM or when navigating to a different route). If it doesn't, you will need to work out a way to only register an event listener once.

+7


source







All Articles