防止$ rootScope.$ on多次调用函数 [英] Prevent $rootScope.$on from calling function several times

查看:139
本文介绍了防止$ rootScope.$ on多次调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在控制器顶部有一个$ rootScope.$ on代码.我注意到,每次加载/调用此控制器时,$ rootScope.$ on侦听器都会增加,这意味着它将在您访问控制器时无限期地添加,添加和添加侦听器.

I have a $rootScope.$on code on top of a controller. I noticed that everytime I load/call this controller, the $rootScope.$on listener increases meaning it will add and add and add a listener, indefinitely as you visit the controller.

当我通过另一个控制器的$ rootScope.$ emit调用它时,我注意到了它,$ rootScope内部的功能.$ on被执行了几次,即使它只是一个单独的发射/广播.

I noticed it when I called it via $rootScope.$emit from another controller, the function inside the $rootScope.$on got executed several times even if it was only a single emit/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 it from creating another listener instance so that when there is already a listener, it won't create a new one.

推荐答案

在破坏控制器的作用域时,您需要注销事件监听器.

You need to deregister the event listener when you controller's scope is destroyed.

$on函数返回一个注销函数,该注销函数将在调用该函数时删除侦听器.

The $on function returns a deregistration function that will remove the listener when the function is invoked.

所以您可以这样设置:

var deregister = $rootScope.$on('listen', function() {
    $scope.displayString();
});
$scope.$on('$destroy', deregister);

注意:这仅在控制器的作用域实际被破坏时才有效(例如,在从DOM中删除的指令中,或者当您导航到其他路线时).如果那没有发生,那么您将需要制定一种只注册一次事件监听器的方法.

Note: this will only work if the controller's scope is actually destroyed (e.g. in a directive that is removed from the DOM or when you navigate to a different route). If that doesn't happen then you will need to work out a way of only registering the event listener once.

这篇关于防止$ rootScope.$ on多次调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆