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 () {
};
const handleKeydown = function (e) {
};
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 () {
isModalOpened = true;
};
const handleKeydown = function (e) {
if (isModalOpened) {
}
};
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:
See also