4R - DOM Custom Events

Define/Explain DOM Custom Events

Custom Events are used to create an event and send custom data from the event. They can be used to trigger from custom events that would not otherwise be triggered by one of the default events. The addEventListener is used with custom events, just like standard events, to listen for the trigger. For custom events, the dispatchEvent method is used to attach the event and activate it.

Define/Explain How to Create Custom Events

Custom events are created by using the CustomEvent() constructor. Inside the () you first create the custom event type (it's name), and after that you pass on the details and options for the event. The detail property contains custom information regarding the event, and the options determine whether or not it bubbles, whether or not it is cancelable, and whether or not it is composed. The syntax is:

var myEvent = new CustomEvent("specialEvent", {
detail: {
msg: "My message",
color: "red",
size: "500"
},
bubbles: true,
cancelable: true,
composed: false,
});

 

Once the event is created, the dispatchEvent method is used to activate the Custom Event. The addEventListener is also used to trigger the listener.

Explain Why DOM Custom Events Are Used

Custom events are used when you want to trigger an event that doesn't exist within the standard events or to trigger an event manually. It allows custom/extra data to be sent along with the event. Because the programmer can define the event and when it executes, there is more control over the event. It also makes the code more flexible to changes that won't affect the event in the future.

Summary

Custom events are a great way to trigger events manually or to make a custom type of event in your code. It allows you to watch for things that wouldn't be triggered by a standard event. Because you can determine if they bubble or not, you can use it to listen to parent elements as well as the current elements or just the current element.

References: