【发布时间】: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