gpt4 book ai didi

angularjs - Angular - 广播,$on 在指令中多次调用

转载 作者:行者123 更新时间:2023-12-04 15:57:30 25 4
gpt4 key购买 nike

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

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

最佳答案

我认为您忘记取消绑定(bind)偶数处理程序。

你可以这样做 -

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

关于angularjs - Angular - 广播,$on 在指令中多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26775628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com