1

I am trying to remove a eventListener that calls an anonymous function with the mouseover and mouseout events.

const playerPlace = (ships,player,computer,ship) => {
    let playerBoard = document.getElementById('playerGameboard');
    playerBoard.addEventListener('mouseover', (e) => playerHover(ship,e))
    playerBoard.addEventListener('mouseout',(e) => playerExit(ship,e))
    playerBoard.addEventListener('click',function(event){
        let element = event.target.id;
        player.playerPlace(ship,parseInt(element[0]),parseInt(element[1]),'horizontal');
        updateGameboard(player,computer);
        ship.isPlacedSetter(true);
        if(isShipPlaced(ships) !== true){
            console.log('remove Listener')
            playerBoard.removeEventListener('mouseover',playerHover);
            playerBoard.removeEventListener('mouseout',playerExit);
            playerPlace(ships,player,computer,isShipPlaced(ships))

        }
    }, {once:true})
} 

I can't find any solutions to my problem online.

QThelp
  • 31
  • 3
  • 1
    Just use a named function and proceed as described in [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener). – Mushroomator Apr 26 '22 at 22:22
  • I would say that you are not the developer that added the listener, is it? – cheesyMan Apr 26 '22 at 22:28
  • @Mushroomator how do I pass a parameter and event to a named function? The ship changes every time there is a click. That does not answer my question as I need to pass a parameter to the function as well – QThelp Apr 26 '22 at 22:28
  • 1
    @KonradLach you can pass extra-parameters to a named function with the `bind()` method – cheesyMan Apr 26 '22 at 22:32
  • 1
    @KonradLach you can still do what you are doing now, just with a named function `test.addEventListener("mouseover", handler = (e) => anotherFunc("test"));`. – Mushroomator Apr 26 '22 at 22:41

1 Answers1

-1

You should use removeEventListener('eventName',function() {/*your anonymus function*/})

user17517503
  • 155
  • 11
  • 2
    This won't work because these won't be the same functions. It only works if you save the function expression in a variable in both places or give the function a name and refer to that later on. – CherryDT Apr 26 '22 at 22:26