Help with removeEventListener

Help with removeEventListener
0

#1

So for my Tic Tac Toe project I’ve used

const spaces = document.querySelectorAll('.col');

spaces.forEach(function(input){ 
   input.addEventListener('click', function playMove() {
     //code  
   })
})

is there a way to remove that listener from within ? I’m having a real brain frazzled day D:

edit: Im able to remove from the last square clicked, but not for all


#2

Something like this?

const box = document.querySelector(".box");

box.addEventListener("mouseover", function callback() {
  alert("Hi!");
  box.removeEventListener("mouseover", callback);
});


#3

Yes this works for single elements and I can use the same idea to remove the event listener from the last space clicked. But as Im using forEach it wont target all the spaces :frowning:


#4

Works for me.
https://codepen.io/Implaier/pen/MOMWmM

Update:
I see what the problem was first solution doesn’t’ work.

Here’s another try.
https://codepen.io/Implaier/pen/NwZWXe

Edit:
To remove a listener the signature must be the same, and the callback function used inside of addEventListener must exist to be referenced later on inside removeEventListener.


#5

Hmm I suppose I could have been clearer, I think its best I just share all the code, as I believe your solution wont work for me,

I want it so after a game has been won squares cant be clicked :thinking:
The forEach method is getting information from the data of the element that is being clicked. I think I need to go sit down and do something different cause my brain is all fog D:


#6

Try adding a flag like this.
https://codepen.io/Implaier/pen/eewzQp

let gameWon = false;
...
input.addEventListener('click', function playMove() {
	if (gameWon) return;
	...
	...
	if(isGameWon()){
			gameWon = true;
	...
	}
}

#7

Yeah it crossed my mind while I was out haha! You wont believe how hard im kicking myself right now :rofl: cheers man @Implaier sometimes you just need that outside view