4R - DOM Custom Events

DOM Custom Events

Custom events can be used to handle scenarios that Javascript is not built to handle by default. You can also customize the data that gets sent from these events.

How to Create Custom Events

Your custom event first needs to be created with the CustomEvent constructor. This constructor will create an object based on the parameters that are passed into it. The first parameter is a string, which will be the name of the event that you want other elements to listen to.

The object that is created by CustomEvent then needs to be dispatched in order for other elements to listen to it. This is done with the dispatchEvent method.

Elements in the DOM are now able to listen to this named event. Using addEventListener, you just have to make sure the event that is being listened to matches the string that was passed into CustomEvent.

Why DOM Custom Events are Used

Custom events are useful if you want complete control over the data that gets sent from a particular event. They are also used for certain scenarios that can happen within your application, that native Javascript is not built to handle.

Summary

Javascript is built to handle a lot of different events, but it cannot handle every single scenario that could possibly happen. This is where custom events can come in and handle events that are unique to your own applications.