AngularJs broadcast repeating execution too many times

好久不见. 提交于 2020-01-09 08:35:49

问题


Inside one of my Angular controllers, I have this:

// controller A
$rootScope.$on("myEventFire", function(event, reload) {
    someAction();
});

In another controller I have this:

// controller B
$scope.openList = function(page) {
    $rootScope.$broadcast('myEventFire', 1);
}

Now, this is a single-page app. When I go to controller A initially and try triggering this event, someAction() is going to be executed once. If I navigate away and come back again to controller A and do the same thing, someAction() gets executed twice. If I do it again, it happens three times and so on. What am I doing wrong here?


回答1:


Can you try just using $scope.$on()? Every time controller A is created, it is adding a new listener on the root scope, and that doesn't get destroyed when you navigate away and back. If you do it on the controller's local scope, the listener should get removed when you navigate away and your scope gets destroyed.

// controller A
$scope.$on("myEventFire", function(event, reload) {
    someAction();
});

$broadcast sends the event downward to all child scopes so it should be picked up on your local scope. $emit works the other way bubbling up towards the root scope.




回答2:


you can also remove it when the scope is destroyed, by running the return callback from the $rootScope.$on().

I.e.

var destroyFoo;

destroyFoo = $rootScope.$on('foo', function() {});

$scope.$on('$destroy', function() {
  destroyFoo(); // remove listener.
});       



回答3:


if you don't want to destroy,

I think we can check the listener event first - AngularJS 1.2.15

So I think this should work :

if(!$rootScope.$$listenerCount['myEventFire']){
    $rootScope.$on("myEventFire", function(event, reload) {
        someAction();
    });
}



回答4:


If it helps anyone I had a similar issue in a directive. Each time the directive opened the number of times the event was fired increased.

I solved it by using the following (this was in my controllers init function but I guess it could have been defined in the controller itself. In my case my controller needed to reinitialise when the event fired)

 if (!$scope.onMyEvent) $scope.onMyEvent= $scope.$on('myEvent',function(event,data){
        .....
        });



回答5:


For my case...

if ($rootScope.$$listenerCount['myEventFire']) {
    $rootScope.$$listeners.broadcastShowMessageError = [];
};

$rootScope.$on('myEventFire', function (event, reload) {
    someAction();
})


来源:https://stackoverflow.com/questions/19553598/angularjs-broadcast-repeating-execution-too-many-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!