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.
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.
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.
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();
});
This seems to do it for me:
var removeListener = $rootScope.$on('submitBookingDialog', function(){
submitBookingDialog();
// Remove listener
removeListener();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With