简体   繁体   中英

I am having trouble " using "removeEventListener()"

This is the original statement which creates the click handlers.

    const cells = document.querySelectorAll(".cell")
    cells.forEach(function(cell) {
      cell.addEventListener('click', onCellClicked.bind(this, cell.id));
    }) 

Below I call the removeEventhandlers() function which contains the method removeEventListener() . How ever this function does not work and does not produce a error message. Can anybody help me rectify this problem?

if (checkForWin(oSelectionArray) === true) {
    insertWinOrLossImage('ticTacToeAssets/Assets/you win image.png', 'youWin', 'playerScore', wonOrLost = winOrLooseObj.won)
    removeEventHandlers()
  } else if (checkForWin(xSelectionArray) === true) {
    insertWinOrLossImage('ticTacToeAssets/Assets/you loose image.png', 'youLoose', 'CPUscore', wonOrLost = winOrLooseObj.lost)
    removeEventHandlers()
  } else if (oSelectionArray.length === 5) {
      insertWinOrLossImage('ticTacToeAssets/Assets/noWinner.png', 'draw', 'drawScore', wonOrLost = winOrLooseObj.draw)
      removeEventHandlers()
     }
   }

function removeEventHandlers() {
  const cellsToRemoveEventhandlers = document.querySelectorAll(".cell")
  cellsToRemoveEventhandlers.forEach(function(cell) {
    cell.removeEventListener('click', onCellClicked.bind(window));
  })
}

You need to keep track of the actual listeners, since .bind creates a new function reference.

Something like this:

let listeners = {};
const cells = document.querySelectorAll(".cell")
cells.forEach(function(cell) {
  const listener = onCellClicked.bind(this, cell.id)
  listeners[cell.id] = listener;
  cell.addEventListener('click', listener);
}) 

function removeEventHandlers() {
    const cellsToRemoveEventhandlers = document.querySelectorAll(".cell")
    cellsToRemoveEventhandlers.forEach(function(cell) {
        const listener = listeners[cell.id];
        cell.removeEventListener('click', listener);
    })
}

Every time you call onCellClicked.bind , you get a newly bound onCellClicked , which is different from any earlier binding. This is why removeEventListener has nothing to remove.

Instead of adding and removing event listeners dynamically, in your case (tic-tac-toe?) it will probably be better to just keep the events bound and check whether the event listener should do anything within the event listener.

The other option is to keep track of the bound event listener functions, but that's more tedious and not worth the while here.

(And one more option is to have the event listener on a parent element and use event bubbling and event delegation.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM