Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(){
    submitBookingDialog();
});

How can I prevent the submitBookingDialog() to happen more than once?

I found a solution, but I don't know if it's ideal.

like image 884
Kitze Avatar asked Jun 30 '14 12:06

Kitze


People also ask

How do I add event listener only once?

Using the once option We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.

Which method can be used to handle an event just only one time?

Using once() Sometimes you want your application to respond to an event (or type of event) only one time (i.e., the first time the event occurs). To do this, Node provides the once() method. It is used just like the addListener() and on() methods, but allows for responding to the event only once.


2 Answers

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(){
    submitBookingDialog();
});

$scope.$on('$destroy', function() {
    // Call the deregistration function when the scope is destroyed
    offSubmitBookingDialog();
});
like image 197
DRiFTy Avatar answered Sep 30 '22 19:09

DRiFTy


This seems to do it for me:

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

    // Remove listener
    removeListener();
});
like image 21
Kim Biesbjerg Avatar answered Sep 30 '22 18:09

Kim Biesbjerg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!