在AngularJS中只注册一次事件侦听器 [英] Register event listener only once in AngularJS
问题描述
我正在从导航栏控制器向另一个控制器广播一个事件,但是如果我多次初始化控制器(当我正在通过应用程序前进和后退时)在我的上执行的函数$ on
事件多次运行,因为它已多次注册。
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();
});
如何阻止 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.
推荐答案
首先,你需要在<$上发送活动吗? C $ C> $ rootScope ?如果没有,那么你可以在 $ scope
上注册你的事件处理程序。每当您的控制器范围被销毁时,事件处理程序都将被销毁。然后,您将通过 $ scope。$ emit
或 $ scope。$ broadcast
发送事件,具体取决于您的控制器层次结构。
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();
});
这篇关于在AngularJS中只注册一次事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!