1

My problem is that I'm trying to remove an event listener on javascript. I had the listener as anonymous as I was passing parameters. The problem is that I have to remove the event listener from all the images later on in my code. I realize I need to re-write my code in order to give it an ID of some kind but I'm really struggling. Here is the part of my code that needs changing, any help will be great.

var images = document.getElementsByTagName("img");
for (var i = 0; i < 4; i++)
{
    listenForI(i);
}

function listenForI(i)
{
    images[i].addEventListener("click",function()
    {
        changeImage(i);
    });
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Dalek
  • 111
  • 4
  • 12
  • @Barmar - the accepted answer is wrong, it's easy to remove an event handler -> **http://jsfiddle.net/t2p50o22/** – adeneo Feb 23 '15 at 22:10
  • 2
    @adeneo Those aren't anonymous, they're named. The reason he's using an anonymous function is because he needs closures that preserve the `i` variable, which your code doesn't do. – Barmar Feb 23 '15 at 22:14
  • @Dalek But adeneo's code shows that you don't NEED to save `i` in your closures. Use a named function, and it can access the image element using `this`. – Barmar Feb 23 '15 at 22:18
  • @Barmar - that was sorta my point, removing all the strange loops as referencing the function gives you `this` instead, and the ability to remove the event handler. There is however an answer showing `removeEventHandler` in that dupe as well, and the question is pretty much exactly the same, it's just the accepted answer that sucks, adding to the "main object" and no code etc. – adeneo Feb 23 '15 at 22:20
  • This is essentially an XY problem. Rather than asking how to remove an anonymous event handler, he should ask how he can use named event handlers to do what he wants. Alternatively, instead of removing the handlers, they could just check a global variable that says whether they're supposed to do anything. – Barmar Feb 23 '15 at 22:23
  • Thanks for the help guys, my code is working now :D. – Dalek Feb 23 '15 at 22:54

0 Answers0