kitze kitze - 11 months ago 72
Javascript Question

Register event listener only once in AngularJS

I'm broadcasting an event from my navbar controller to another controller, but if i initialize the controller multiple times (when i'm going front and back through the application) the function that executes on my $on event runs multiple times because it's registered multiple times.

$rootScope.$on('submitBookingDialog', function(){

How can i prevent the submitBookingDialog() to happen more then once?


I found a solution here, i don't know if it's ideal but anyway it works

Answer Source

First of all, do you need to send the event on the $rootScope? If not, then you could just register your event handler on the $scope. The event handler will be destroyed whenever your controller scope is destroyed. You would then send the event via $scope.$emit or $scope.$broadcast depending on your controller hierarchy.

That being said, all you need to do to destroy your event listener is call the deregistration function that is returned when registering the listener:

var offSubmitBookingDialog = $rootScope.$on('submitBookingDialog', function(){

$scope.$on('$destroy', function() {
    // Call the deregistration function when the scope is destroyed