Angular - 广播,在指令中多次调用 $on [英] Angular - broadcast , $on called multiple times in directive

查看:34
本文介绍了Angular - 广播,在指令中多次调用 $on的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a single page app, with angular and I have a need to communicate between 2 different directives which basically don't have a parent child relation.

在指令 A 中,我有两个地方需要从不同的函数广播相同的事件.在指令 B 中,为此编写了一个 $on 侦听器.

In Directive A, I have 2 places where I need to broadcast same event from different functions. And in Directive B, have written a $on listener for that.

现在,我观察到每当 callFirstFunc &第一次调用它的广播,监听器将被调用一次.在随后的调用中,监听器被调用两次,三次,以此类推,不断增加.

Now, I observe that the whenever callFirstFunc & its broadcast is called for first time, the listener will be called once. Upon subsequent calling, the listener is called twice, thrice and so on ,it keeps on increasing.

callSecondFunc 在 callFirstFunc 执行时被调用,所以这个监听器也被调用了很多.在 callFirstFunc 中广播的侦听器的次数.那么,为什么侦听器不是只调用一次,而是多次调用呢?它每次都在循环和增加.

The callSecondFunc is called when the callFirstFunc has been executed, so the listener for this is also called as many no. of times the listener for broadcast in callFirstFunc. So, why is the listener not called only once, why multiple times? It is looping and increasing every time.

指令 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
               }                    
            }
        };
    });

推荐答案

我想你忘了解除偶数处理程序的绑定.

I think you forgot to unbind the even handler.

你可以像下面那样做 -

You can do it like following -

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

这篇关于Angular - 广播,在指令中多次调用 $on的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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