Search code examples
javascriptdomweb-component

Web component element click event listener not working


I am creating a simple Rock, Paper, Scissors game.

I have decided to not use any framework, so I'm doing it completely in pure JavaScript, using Web Components.

I've manage to do pretty much everything what I wanted, but there is a component (ResultDisplay) on which for some reasons click events do not work on replay and reset buttons.

It's very strange, because I have a very similar component just near it (StartCounter) which has a button click listener and there it works perfectly!

I don't understand what I'm missing...

_initEventListeners() {
  // This is always called.
  this.replayButton.addEventListener('click', this._onReplayClick.bind(this));
  this.resetButton.addEventListener('click', this._onResetClick.bind(this));
}

_onReplayClick() {
  // This is never called when I'm clicking on the button.
  this.triggerEvent('replay');
}

I cannot put the entire code here, it would be too hard to read.
But you can find it all here and even test it yourself with npm run dev

Any idea is much appreciated.


Solution

  • In your code, you add the event listeners to the buttons inside the initial <result-display> content.

    However, when you want to display the result of the first game, you call createTemplate() again, which recreates a new DOM in the shadowRoot with new buttons, with no event listeners attached to them.

    You sould then call _initEvenListeners() again.