4/121

Attach event handlers inside other handlers

Usually, there are many event handlers which handle different events for different elements. These events could depend on each other.

Let's look at a common use case. When user clicks a button, we will open a modal at the center of screen. The modal can be closed by pressing the Escape key.

There are two handlers here:

  • The first one handles the click event of the button
  • The second one handles the keydown event of the entire document

We often create two separated handlers as following:

const handleClick = function() {
    // Open the modal
};

const handleKeydown = function(e) {
    // Close the modal if the Escape key is pressed
};

// Assume that `buttonEle` represents the button element
buttonEle.addEventListener('click', handleClick);
document.addEventListener('keydown', handleKeydown);

The handleKeydown handler depends on handleClick because we only check the pressed key if the modal is already opened. It's a common way to add a flag to track if the modal is opened or not:

let isModalOpened = false;

const handleClick = function() {
    // Turn on the flag
    isModalOpened = true;
    // Open the modal ...
};

const handleKeydown = function(e) {
    // Check if the modal is opened first
    if (isModalOpened) {
        // Check the pressed key ...
    }
};

More elements, more dependent events and more flags! As the result, it's more difficult to maintain the code.

Instead of adding event separately at first, we add an event handler right inside another one which it depends on. Here is how the tip approaches:

const handleClick = function() {
    document.addEventListener('keydown', handleKeydown);  
};

No flag at all! The code is more readable and easier to understand.

Use cases

You can see the tip used in another posts:

Might be useful