Home > Web Front-end > JS Tutorial > body text

How to Avoid Closure Issues When Using Event Listeners in a Loop?

Susan Sarandon
Release: 2024-11-21 16:32:11
Original
740 people have browsed it

How to Avoid Closure Issues When Using Event Listeners in a Loop?

Avoiding Closure Issues When Using Event Listeners in a Loop

In your attempt to attach event listeners to multiple elements using a for loop, you've encountered the issue where all listeners end up targeting the last object. This is due to the way closures work in JavaScript.

Understanding Closure

When a function refers to a variable declared outside its scope, it retains access to that variable even after the function exits. In your case, the event listener functions defined within the loop reference boxa and boxb, which are defined outside the loop. When the loop completes, these variables point to the last elements in the loop.

Fixing the Issue

To avoid this closure issue, you can use an immediately invoked function expression (IIFE) inside the loop. An IIFE creates a new scope, so the variables declared within it are not accessible outside the function.

Revised Code

Here's the revised code with the IIFEs in place:

// Function to run on click:
function makeItHappen(elem, elem2) {
  var el = document.getElementById(elem);
  el.style.backgroundColor = "red";
  var el2 = document.getElementById(elem2);
  el2.style.backgroundColor = "blue";
}

// Autoloading function to add the listeners:
var elem = document.getElementsByClassName("triggerClass");

for (var i = 0; i < elem.length; i += 2) {
  (function () {
    var k = i + 1;
    var boxa = elem[i].parentNode.id;
    var boxb = elem[k].parentNode.id;
    elem[i].addEventListener("click", function() {
      makeItHappen(boxa, boxb);
    }, false);
    elem[k].addEventListener("click", function() {
      makeItHappen(boxb, boxa);
    }, false);
  }()); // immediate invocation
}
Copy after login

By using the IIFEs, you ensure that each event listener function has its own scope, preventing the closure issue. Now, each event listener will correctly target the corresponding element within the loop.

The above is the detailed content of How to Avoid Closure Issues When Using Event Listeners in a Loop?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template