【问题标题】:Angular - broadcast , $on called multiple times in directiveAngular - 广播,$on 在指令中多次调用
【发布时间】:2015-01-02 17:35:11
【问题描述】:

我正在开发一个带有角度的单页应用程序,我需要在 2 个基本上没有父子关系的不同指令之间进行通信。

在指令 A 中,我有 2 个地方需要从不同的功能广播相同的事件。在指令 B 中,为此编写了一个 $on 监听器。

现在,我观察到只要 callFirstFunc 及其广播第一次被调用,监听器就会被调用一次。在随后的调用中,监听器被调用了两次,三次等等,它一直在增加。

callSecondFunc 在 callFirstFunc 被执行时被调用,所以这个监听器也被称为尽可能多的 no。 callFirstFunc 中广播的监听器次数。 那么,为什么监听器不是只调用一次,为什么是多次呢?它每次都在循环和增加。

指令 A:

app.directive("firstDir", function ($rootScope) {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            // some other code
            callFirstFunc();
            var callFirstFunc = function(){
                // some other code
                $rootScope.$broadcast("someEvent");
            }
            callSecondFunc();
            var callSecondFunc = function(){
                // some other code
                $rootScope.$broadcast("someEvent");
            }
        }
    };
});

指令 B:

app.directive("secondDir", function ($rootScope) {
        return {
            restrict: 'E',
            link: function (scope, element, attrs) {
                // some other code
                scope.$on("someEvent", function(){
                    detectSTuff();
                }) 
               function detectStuff(){
                  // other code
               }                    
            }
        };
    });

【问题讨论】:

标签: angularjs angularjs-directive angularjs-scope angular-broadcast


【解决方案1】:

我想你忘记取消绑定偶数处理程序了。

你可以这样做 -

var someEventHandle = scope.$on("someEvent", function(){
                    detectSTuff();
                });
scope.$on('$destroy', someEventHandle);

【讨论】:

  • Rabi - 我试过了,但还是一样。它不止一次地收听并不断增加。
【解决方案2】:

此代码适用于我:

$rootScope.$$listeners.nameOfYourEvent.length = 1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多