Wrap addEventListener in a Function for More Control

Share this video with your friends

Send Tweet

As we develop our pattern further, we can see how it can apply to all async scenarios in JavaScript. All user events go through addEventListener, so making sure we have control over how addEventListener interacts with other APIs, like setTimeout, gives us confidence in our pattern moving forward.

Brian Zelip
Brian Zelip
~ 4 years ago

Here is the nested arrow function addLisetner rewritten with non-arrow functions:

function addListener(selector) {
  return function (eventType) {
    return function (listener) {
      let element = document.querySelector(selector);
      element.addEventListener(eventType, listener);

      return function () {
        element.removeEventListener(eventType, listener);
      };
    };
  };
}