DEV Community

Cover image for Design patterns: Event delegation for cleaner, more concise code.
Joshua Ng'ang'a Raphael
Joshua Ng'ang'a Raphael

Posted on

Design patterns: Event delegation for cleaner, more concise code.

Event delegation is a design pattern where an event listener is applied to a parent element container instead of applying one to each individual child element. Events that occur within the children elements are then handled by the parent element.

Day to day event delegation

In a given office,the manager may be placed in charge of several groups of workers. The number of workers may be too many for the manager to individually handle and supervise. Rather than individually micromanaging each worker, the office manager may assign team leaders to each group of workers.
With the appointment of team leaders, the manager who now represents our parent element can then assign tasks to each team through the team leaders who represent event listeners attached to our parent element (manager) and receive feedback from the multiple workers who represent our children elements via the assigned team leaders.
Similarly, in event delegation we attach an event listener to our parent container rather than to each individual child element. An event that occurs to any of the children elements is bubbled up to the parent element and the parent's event listener handles it.

Use cases for event delegation

In this article we showcase an example of event delegation implemented using JavaScript.
We attach an event listener to the 'Ul' parent element using its id selector 'Parent on which upon the occurrence of a click event, our function checks if the element clicked on is a 'li' element. If the element is confirmed as a list item, it has its CSS class 'highlight' toggled to an either active or inactive state.

Why use event delegation?

The ability to manipulate the behavior of multiple elements using only one event listener (dynamic contextual handling) is just but one of the benefits offered by event delegation. Event delegation is also advantageous by providing;

  • Cleaner, more concise code - providing an easily maintainable codebase.
  • Reduced memory consumption - arising as a result of fewer attached event listeners.
  • Flexibility and scalability - as events in large scale applications are more easily handled.

In this article we discuss event delegation and showcase one of its use cases in handling (dynamic contextual handling) using a single event listener attached to a parent element.

Event delegation is definitely one of the more simpler design patterns programmers should look to implement in an attempt to improve the quality of their code.

Top comments (0)