如何删除作为匿名函数的事件侦听器?

How can I remove an event listener that's an anonymous function?

我已经在 angular 应用程序的 iframe 中实现了一个 html5 迷你游戏,但是从中接收数据一直很麻烦。我以为我让它与事件侦听器一起工作,但现在它在打开页面时创建了一个,但在关闭页面时不会将其删除。所以现在重新打开页面会保留多个事件侦听器。

因为我想要事件中的数据,并且我想使用同一事件中的其他函数class,我是这样实现的

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' 未定义,因为当通过事件监听器执行时,它不再在范围内。

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

中调用方法

在此先感谢,过去几个小时我一直在为这个问题伤脑筋。

按要求编辑原始代码

@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]);
    }
}

你不能用匿名函数来做。您必须引用监听器函数。

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