Understanding Events- The Final Act

Rajashree Parhi
Behind the Tech — Chainwhiz
4 min readSep 5, 2022

Oh, and how we’ve reached the Very End.

Written by — Rajashree Parhi| Edited by — Arka Sengupta

If you’ve got a strong memory, then you shall remember that a built-in event can be triggered by the action of the user. For example, the clicking of the mouse button, the tapping of the keyboard, or touching the touch-sensitive surface are some of the built-in events that help determine what exactly happens in an application.

However, at times, the built-in events aren’t adequate to track the state of an application. For example, while using an e-commerce website we click on an object and it gets added to the cart. Simple, right? But, the display of the total items added to the cart is handled by the parent component. So, we want to inform the parent component to update its values i.e. ‘An item has been added, please show the updated count’. And, do we have any such update-cart event to dispatch? Alas!

But, in steps — Custom Events to save the day and rule the Seven Kingdoms!

How to create custom events in JavaScript?

There are a couple of ways we can go about this —

  1. Event constructor
  2. CustomEvent constructor

Event constructor

In the above snippet, we created an event, newevent, by passing the event name to the Event constructor. Event names are case-insensitive, so newevent is the same as newEvent and NewEvent, etc.

bubbles- It specifies whether the event should propagate upward to the parent element. For most native DOM events, it’s true but for the custom event, it’s false by default.

If you want to understand what event bubbling is head over here.

cancelable- As the name suggests, it denotes whether the event should be cancelled. Native DOM elements are cancelable by default. That’s why we can use event.preventDefault() to prevent the default action of the event. If the custom event has cancelable set to false, calling event.preventDefault() will not perform any action.

composed- It specifies if an event should bubble across from shadow DOM. But, if ‘bubbles’ is set to false, the value of ‘composed’ doesn’t matter

A quick explanation of shadow DOM- It helps in encapsulating part of the DOM tree that can’t be accidentally accessed from the main document.

CustomEvent constructor

As shown above, creating a custom event via the CustomEvent constructor is similar to creating one using the Event constructor.

The only difference is in the object passed as the second parameter to the constructor i.e detail. Using detail, we can pass data to the listener.

This is an added advantage over the Events constructor because in most use cases we would like to send data across from where the event is being dispatched to the listener.

How to dispatch an event?

  1. We created a custom event using CustomEvent.
  2. We dispatched the custom events to the target using dispatchEvent()
  3. We added an event listener to the element we wanted to listen on.

Here’s a quick example

I have made a to-do list in which the count of the total tasks remaining decreases every time we strike off a task!

Source- https://github.com/rajashree23/events/tree/master/UnderstandingEvents-Part3
Source- https://github.com/rajashree23/events/tree/master/UnderstandingEvents-Part3
Source- https://github.com/rajashree23/events/tree/master/UnderstandingEvents-Part3

Every time we click on any of the items the task gets struck off, denoting a completed task.

I have attached an event listener on the ‘list’. The handler does two things- one it adds a ‘completed’ CSS class to the target element and second, it dispatches a custom event that handles decreasing the task count.

You might have a question that we could have simply decreased the count just after CSS class addition instead of having a Custom Event. Definitely, yes we could have done that. But my purpose over here is to show how you can use the Custom Events to decouple the code you want to execute after another piece of code completes.

Demo

Initial state
After clicking on 3 and 4

Quick Fact: Custom events are also known as ‘synthetic events’

Closing thoughts

Custom events help in separating out events that help in maintaining large codebases. For example, we can separate the event listeners in a separate script. In addition, we can have multiple event listeners to the same custom event. These are just a few of the advantages of Custom Events. Top JavaScript frameworks like VueJS, expressJS make heavy use of custom events .

Feel free to play around with my code for better understanding — https://github.com/rajashree23/events/tree/master/UnderstandingEvents-Part3 😄

If you want to catch up on my previous articles about Understanding Events, follow the links below —

Part 1- https://medium.com/behind-the-tech-chainwhiz/understanding-events-part-1-6624900e3f4

Part 2- https://medium.com/behind-the-tech-chainwhiz/understanding-events-part-1-6624900e3f4

Follow Chainwhiz’s publications for constant updates and new articles!

Twitter | LinkedIn | GitHub

--

--