Why, using @HostListener, keypress event fires a number of time equal of the times the page is visited (ionic2/typescript)?

点点圈 提交于 2021-02-10 14:13:36

问题


I have a page in ionic 2 and I want to catch key pressed when the user is in the page. This is the code I used to do this (.ts)

@Component({
  selector: 'page-play',
  templateUrl: 'play.html'
})

export class PlayPage {
  @HostListener('document:keypress', ['$event'])
  handleKeyboardEvents(event: KeyboardEvent) {
    console.log("keypressed!");
  }

  constructor() {
    // doing a lot of things
  }
}

Unfortunately, the handleKeyboardEvents gets fired once the first time I enter in the page, twice if, after that, i navigate some other pages in the app and then go back to the page, three times if I exit and enter again and so on...

What can cause this?

EDIT: In the end, in my case, it turned out that the problem was that I was 'stacking' multiple times that page. The flow of the application was something like

Homepage -> Play Page -> EndPlay Page (and if you choose to play again) -> Play Page

The Play Page was presented again with a second 'push' (this.navCtrl.push) so to appear multiple times in the stack and, every one of it, had is own HostListener, firing events.

I've not yet come out with a clean solution for I don't really know how to manage correctly the stack, so I won't propose a real code solution for this. In some way, the solution is avoiding to push multiple times a page.

来源:https://stackoverflow.com/questions/45508829/why-using-hostlistener-keypress-event-fires-a-number-of-time-equal-of-the-tim

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!