我在我的 angularjs 应用程序中使用 $broadcast 和 $emit 。这是我注册 $emit 函数的代码:
this.scope.$emit('changeTime', {
currentTime: this.currentTime
});
在另一个 Controller 中,我正在监听此发射函数以返回如下对象:
this.scope.$on('changeTime', (event, args) => {
console.log(args.currentTime);
});
这里一切正常。 但是这个监听器正在调用我的不同函数,该函数根据不同的条件调用:
this.functionone(){
this.scope.$on('changeTime', (event, args) => {
console.log(args.currentTime);
});
}
this.functiontwo(){
this.scope.$on('changeTime', (event, args) => {
console.log(args.currentTime);
});
}
当我调用控制台中打印的当前时间的第一个函数时。当我的条件发生变化并调用另一个函数 functiontwo() 时,我还可以看到 functionone 控制台值。
意味着当第二个函数在一次之后被调用时,changetime 监听器调用两次。
那么我如何取消注册这个之前称为“changetime”的内容。所以第二次就没有来了。
最佳答案
按设计listeners
/$watch
函数返回取消注册函数。因此,您可以通过直接调用 dereigster 函数来取消注册事件(如果存在)。
this.functionone = function(){
this.deregisterEvents();
this.eventOneChangeTime = this.scope.$on('changeTime', (event, args) => {
console.log(args.currentTime);
});
}
this.functiontwo = function(){
this.deregisterEvents();
this.eventTwoChangeTime = this.scope.$on('changeTime', (event, args) => {
console.log(args.currentTime);
});
}
deregisterEvents(){
//unregistering events.
if(this.eventOneChangeTime) this.eventOneChangeTime();
if(this.eventTwoChangeTime) this.eventTwoChangeTime();
}
关于javascript - AngularJs 销毁广播并发出监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42689228/