Home > Web Front-end > JS Tutorial > How to Assign Event Listeners to Multiple Objects Without Scope Conflicts?

How to Assign Event Listeners to Multiple Objects Without Scope Conflicts?

Patricia Arquette
Release: 2024-11-20 17:30:11
Original
370 people have browsed it

How to Assign Event Listeners to Multiple Objects Without Scope Conflicts?

Event Listener Assignment Using Iterative Functions

When using a loop to add event listeners to multiple objects, it may appear that all listeners reference the same object, typically the last one in the loop. This is because of how JavaScript handles variable scope and function closures.

To address this issue, employ the following approach:

// 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);
  }());
}
Copy after login

In this code, an anonymous function is wrapped around the inner scope, creating a closure for each iteration. By executing the function immediately with the '()' operator, each iteration has its own private scope, ensuring that the variables and functions within don't interfere with those of other iterations.

This approach grants each event listener access to its intended variables, resolving the issue of all listeners targeting the same object.

The above is the detailed content of How to Assign Event Listeners to Multiple Objects Without Scope Conflicts?. 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