How to use the arrow function as a callback to the event listener

Time:2021-8-4

Arrow function

ES6 introduces the concept of arrow function, which is a new method to define and write functions. Although it looks like a syntactic sugar of conventional functions, the key difference between them is the rightthisBinding method of. This article does not coverthisA lot of details

Event listener callback

When writing JavaScript to browsers, we often create event listeners. For example:

const toggleElements = document.querySelectorAll('.toggle');
toggleElements.forEach(el => {
  el.addEventListener('click', function() {
    this.classList.toggle('active');
  });
});

In the above example, thenodelist.prototype.foreach()To traverse with the specified selector andeventtarget.addeventlistener()Match the nodes and use the conventional function as theclickThe callback of event exchange, which is used to transition between the active and inactive states of the click element. When using a regular function, thethisWill be bound to the element that triggers the event.

Use the arrow function as a callback

The arrow function does not have its own bound tothis。 So what happens if you convert the previous code snippet into an arrow function? itsthisThe point is globalwindowObject.

const toggleElements = document.querySelectorAll('.toggle');
toggleElements.forEach(el => {
  el.addEventListener('click', () => {
    this.classList.toggle('active'); // “ "This" points to "window"
    // Error: Cannot read property 'toggle' of undefined
  });
});

becausewindowObject does not haveclasslistProperty, so whenever you click the matching element, the code throws an error, triggering the event listener and executing the callback. But in general, the code may fail silently. For example, it may check a condition that determines whetherwindowAlways return asfalseFor a given element, it should returntrue, this will cause a lot of trouble and waste your time.

To solve this problem, you can simply use the first parameter of the callback function andevent.targetorevent.currenttarget, which one to use depends on your needs:

const toggleElements = document.querySelectorAll('.toggle');
toggleElements.forEach(el => {
  el.addEventListener('click', (e) => {
    e.currentTarget.classList.toggle('active'); //  Normal operation
  });
});

How to use the arrow function as a callback to the event listener


This article starts with WeChat official account: front-end pioneer.

Welcome to scan the two-dimensional code to pay attention to the official account, and push you every day to send fresh front-end technical articles.

How to use the arrow function as a callback to the event listener


Welcome to continue reading other high praise articles in this column: