How to use arrow functions as callbacks for event listeners

Time:2022-11-25

arrow function

ES6 introduces the concept of arrow functions, a new way of defining and writing functions. While it may seem like syntactic sugar for regular functions, the key difference between them is the need forthisthe binding method. This article will not deal with thethislots of detail

event listener callback

When writing JavaScript for the browser, we often create event listeners. E.g:

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

In the example above, usingnodelist.prototype.foreach()to iterate over the specified selector andeventtarget.addeventlistener()matching nodes, and use regular functions asclickCallback for event exchange, this callback is used to switch between the active and inactive states of the clicked element. When using regular functions, the callback’sthisWill be bound to the element that triggered the event.

Using arrow functions as callbacks

An arrow function has no binding of its own tothis. So what would happen if we converted the preceding code snippet into an arrow function? itsthispoint to the globalwindowobject.

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

becausewindowobject does not haveclasslistattribute, so whenever a matching element is clicked, the code throws an error, which triggers the event listener and executes the callback. But in general, code may fail silently, for example it may check a condition that evaluates towindowalways returns asfalse, while for a given element it should returntrue, which can cause a lot of trouble and waste your time.

To fix this, simply pass the callback function’s first parameter 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'); // works fine
  });
});

How to use arrow functions as callbacks for event listeners


This article is the first WeChat public account: front-end pioneer

Welcome to scan the QR code to follow the official account, and push you fresh front-end technical articles every day

How to use arrow functions as callbacks for event listeners


Welcome to continue reading other highly praised articles in this column: