这个问题在这里已有答案:
我已经在一个角度应用程序中将html5迷你游戏实现为iframe,但是从它接收数据一直很麻烦。我以为我使用了eventlistener它,但是现在它在打开页面时创建一个,但是在关闭页面时不会删除它。所以现在重新打开页面会留下多个事件监听器。
因为我想要来自事件的数据,并且我想使用同一类中的其他函数,所以我已经像这样实现了它
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'未定义,因为当通过eventlistener执行时,它不再在范围内。
有人知道删除匿名eventlistener的方法,或者为eventlistener提供一个函数,同时它仍然可以在同一个类中调用方法吗?
在此先感谢,在过去的几个小时里,我真的一直在打破这个问题。
根据要求编辑原始代码
@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
将结果存储在变量中,也可以使用箭头函数(如果有)。