【问题标题】:How can I remove an event listener that's an anonymous function? [duplicate]如何删除作为匿名函数的事件侦听器? [复制]
【发布时间】:2019-04-12 14:46:47
【问题描述】:

我已经在一个 Angular 应用程序的 iframe 中实现了一个 html5 小游戏,但是从它接收数据一直很麻烦。我以为我可以使用事件监听器,但现在它在打开页面时会生成一个,但在关闭页面时不会将其删除。所以现在重新打开页面会留下多个事件监听器。

由于我想要事件中的数据,并且我想使用同一类中的其他函数,所以我已经这样实现了它

ngOnInit(){
window.addEventListener('message', (event) =>{
//do some stuff
this.someMethodINeed();
}

}

但现在我无法删除此侦听器,因为该函数是匿名的。 我希望它像这样实现:

ngOnInit(){
window.addEventListener('message', this.handleEvent);
}

public handleEvent(event){
//do some stuff
this.someMethodINeed();
}

public navigate(path: string){
window.removeEventListener('message', this.handleEvent);
//navigate logic
}

但现在它抱怨“this”未定义,因为当通过事件监听器执行时,它不再在范围内。

是否有人知道删除匿名事件侦听器的方法,或者 给事件监听器一个函数,同时它仍然可以调用同一个类中的方法?

在此先感谢,在过去的几个小时里,我真的一直在思考这个问题。

根据要求编辑原始代码

@Component({
  selector: 'seed-minigames',
  templateUrl: './minigames.component.html',
  styleUrls: ['./minigames.component.scss']
})
export class MinigamesComponent implements OnInit {
  constructor(public navigationService: NavigationService, public router: Router, private minigamesService: MinigamesService) {
}

  ngOnInit() {    
      var minigameServerAdress = this.minigamesService.MinigameServerAdress();
      //makes url for specific user, which sends user id
      var url = this.minigamesService.makeUrl();
      //set the iframes source to that url
      document.getElementById('minigame-iframe').setAttribute( 'src', url);
        //adding listener which listens for scores from the minigame, after the minigame page has been opened
        window.addEventListener('message', (event) => {
            //check the origin of the data
            if (~event.origin.indexOf(minigameServerAdress)) {
                //navigate to the homepage if the game is closed
                if(event.data == "exit"){
                    this.navigate(' ')
                }
                //otherwise procces the data as scores.
                else{
                    this.minigamesService.sendScores(event.data);
                }

            } else { 
                //the source wasnt confirmed, the data wasnt from our server, so we wont use this data.
                console.log("cant confirm source: "+ event.origin);
                return; 
            }
        }); 
  }

      // Navigate to a specific path.
      public navigate(path: string) {
        //this should remove the event listener, but im not sure how yet.
        // Navigate to 'path'
        this.router.navigate([path]);
    }
}

【问题讨论】:

  • 欢迎来到stackoverflow:你能粘贴完整的代码吗?
  • 只需从this.handleEvent 中删除this.
  • 那行不通,因为 addEventHandler 在 angular 的 init 方法中,忘记在代码片段中显示,现在编辑它:)

标签: javascript removeeventlistener


【解决方案1】:

你不能使用匿名函数来做到这一点。你必须有一个监听器函数的引用。

关于 this 未定义的问题——这是 JS 中的一个常见问题,值得用谷歌搜索一下。您可以使用bind 并将结果存储在变量中,或者如果您有箭头函数,也可以使用它们。

【讨论】:

  • 谢谢,在考虑了放置它的位置后,我用一个相当简单的方法修复了它:this.handleEvent = this.handleEvent.bind(this);
猜你喜欢
  • 1970-01-01
  • 2011-03-07
  • 2010-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-10
相关资源
最近更新 更多