Event Delegation was something introduced to my vocabulary whenever I was trying to create a calculator. Essentially it is a way to create one handler that reacts based off the event.target.
Here I created the eventListener on the common parent for all of the targets that this click might apply to. From here you are able to capture the clicked element by checking the event.target. Then you can use something like an if statement to specify what happens depending on what target was found.
$buttonsContainer.addEventListener('click', event => {
if (event.target == $clearButton) {
clearScreen()
}
})
Something to take note of when working with event delegation. Lets say you are working with a 'ul' and thats where your eventListener is setup. You then write different conditionals for all of your 'li's to trigger certain effects. The problem arises when the 'li' has a child element. If you were to click on this child element it wouldn't recognize the conditional set to its parent.
In order to account for this in your code you could use the attribute .closest('li'). You also want to make sure that the 'li' you found using .closest is within the correct 'ul'. In order to accomplish this you can use .contains(), which would look something like $myUl.contains(the closest 'li' I found).
Overall event delegation is very useful if you are trying to listen for events on multiple elements of the same parent. It will save you quite a bit of memory if you only have the single event listener on the parent, compared to putting an event listener on each individual child element.
Top comments (0)