Home > Back-end >  Failed to store the reference of event handler (I want to remove the event listener)
Failed to store the reference of event handler (I want to remove the event listener)

Time:02-05

As the following code, when I click the "play round" button, it add an click event listener for each three options: Rock, Paper and Scissors. When they are ready, they turn to yellow.

When player pick one of them, the event listener need to be removed (prevent from miss click again).

According to this answer enter image description here

enter image description here

When I go back to playRound function, I'm sure that selection.clickHandler attribute well setted. enter image description here

enter image description here

Anyone knows what's wrong?

CodePudding user response:

Just store your handler before adding the eventListener:

const playerSelection = function(selected, selections) {
    selected.id = 'selected';
    selections.forEach((selection) => {
        selection.classList.remove('listening');
        // get the anonymous event handler by cached reference
        selection.removeEventListener('click', selection.clickHandler, false);
    }); 
}

const playRound = function() {
    const selections = document.querySelectorAll(".selection");
    selections.forEach((selection) => {
        selection.id = undefined;
        selection.classList.add('listening');
        selection.clickHandler = function() {
            playerSelection(selection, selections);
        }
        selection.addEventListener('click', selection.clickHandler, false);
    });
};

const round = document.querySelector(".round");
round.addEventListener('click', playRound);
.selection,
.round {
    width: 100px;
    height: 50px;
    border: 1px solid black;
    background-color: white;
}

.selection.listening {
    background-color: yellow;
}

#selected {
    background-color: red;
}
<div data-name="Rock" >Rock</div>
    <div data-name="Paper" >Paper</div>
    <div data-name="Scissors" >Scissors</div>
    <div >Play a round</div>

  •  Tags:  
  • Related