4R - DOM Custom Events

DOM Custom Events

The DOM CustomEvent is a constructor that creates a new CustomEvent object. There are two parameters with Custom Events which include the type which is a string that provides the elements name and the options which is an object that contains the detail property which has any information that is about the event.

How to Create Custom Events

To create custom events you have to use the Event constructor which is const event = new Event("build") and then add the element add event listener elem.addEventListener and the element.dispatchEvent(event). The addEventListener method creates a function that is going to be called when the given event is brought to the target which can be an element, document, window or elements children. The dispatchEvent method is used to send a Event to a given object which calls the EventListener to action in the order it was written.

Why DOM Custom Events are used

DOM Custom Events are used to seperate code that you are going to perform after a different piece of code is completed. For example when creating a custom event you want to be able to create an event that does something specific and triggers whenever you want. Custom Events allow this to happen simply by adding the HTML element to the web page by using CustomEvent or the Event Constructor.

Summary

DOM Custom Events are created either by using the event constructor or the CustomEvent constructor. To dispatch custom events an EventTarget constructor is used. After dispatching an event, listening to an event occurs where a .addEventListener is used to call the given event to be brought to the target.