Useful Introduction to Web Custom Events
Browser events, otherwise DOM events are actions which are executed by the browser / system or asynchronously by a user interaction with some part of the DOM.
They are buildin events like
keyup and custom events which can be created by the web application developer.
There are some things, we should consider when using events.
Event Capturing and Event Bubbing
In Event handling there are two phases the capturing and the bubbling.
- Event Capturing
When an element is clicked the browser checks if the parent
<html>element has a registered event handler for click, then moves to the immediate child elements and makes its way checking until it checks the clicked element.
- Event Bubbling
Is the reverse of the event capturing, starts from the clicked element and checks all the way to
They are generally the events which live in the browser, based on DOM specifications. They have no standard way to categorize them, since you can find for example Networdk based events like
offline but also you can find resources related with Element focus like
blur. If I have to say a way to categorize all these, I would say that their categories are based on the resource they are using. For example if we take the
open event of the Websocket related events, to use it we must, firstly instantiate a Websocket and then listen for the
open event to start communicating with the Websocket.
You can find more information here.
A custom event is created by instanciating the Event Class / Interface passing the event’s name as a string with the constructor.
const MyEvent = new Event('mycustomevent');
Dispatch Event (Broadcast to the application)
HTMLElement.dispatchEvent( Event eventinstance );
To dispatch an event, you should have access to its instance, you can’t broadcast using the event’s name as a string.
Wrong Way (This don’t work)
const myelem = document.querySelector('#myelem'); myelem.dispatchEvent('mycustomevent');
const myCustomEvent = new Event('mycustomevent'); const myelem = document.querySelector('#myelem'); myelem.dispatchEvent(myCustomEvent);
Also keep in mind that event listeners must defined before the dispatchEvent in the execution stack in order to work.
Where to use Custom Events
Custom events came along with the Web Components API. Which is a way to define custom elements for our web application and simplify our HTML code by providing more specific syntax. So custom events are usually defined inside a custom HTML element, in order to listen for a special action. For example, if we have modal defined as custom element, we have to define the
close events as custom events to allow integration with other parts of the application. Without messing with the code of the custom element, making it limiting its reusability.