Search code examples
javascriptjquerychess

How can I remove multiple event listeners using a for loop?


I'm creating a chess program to test my javascript abilities. It doesn't have any AI, just calculates which moves can be performed at any given time, allows the player to execute the move, and changes turns.

Here's a JSFiddle with the current program: https://jsfiddle.net/1xe7ca00/

The game mechanics are as follows:

1) firstEventListener places an event listener on all pieces which are eligible to move:

divChessboardContainer.addEventListener("click", firstEventListener, true);

2) The user clicks an eligible piece. They can click through multiple pieces if they want.

3) The program collects data from event.target (removeAddClassesReturnPieceData), checks which piece has been selected and identifies which moves can be performed by that piece (ifWhitePawn, ifBlackKnight, etc), and highlights in green the proposed moves (generateObjectForSecondEventListener).

4) Each proposed move highlighted in green has an event listener placed on it:

proposedPositionElement.addEventListener("click", movePieces.bind( null, objectForSecondEventListener, proposedPositionElement ), false);

5) The user clicks a proposed move and the move is executed (movePieces). For the moment it just swaps the IMG tags of the selected piece and the proposed position.

6) The problem I'm having is that I want to remove the second event listener from all the squares which were previously highlighted in green at the end of each turn, but I can't seem to remove it. I've researched the removeEventListener() method and I know that the syntax has to be very specific to work correctly, but I can't work out what I'm doing wrong. Here's a for loop that I've created to try to remove the event listeners (which doesn't work):

for ( let i = 0; i < allListTags.length; i += 1 ) {

    let proposedPositionElement = allListTags[i];

    console.log(proposedPositionElement);

    proposedPositionElement.removeEventListener("click", movePieces, false);

}

Can anyone help me out?


Solution

  • In step 4, you bind an event to movePieces.bind(...), and in step 6, you try to remove the movePieces listener. These are different functions. Also, trying to remove movePieces.bind(...) won't work either, because that'll create yet a third function. You need to store the bound function reference somewhere in step 4 and retrieve it in step 5.