Custom Event
Overview
Custom events in JavaScript provide developers with the ability to create their own events that can be triggered and listened to within an application. This feature is particularly useful for decoupling code and creating more modular applications. By using custom events, developers can signal that a specific condition has occurred without needing to know which part of the code will handle the event. This allows for more flexible and maintainable code structures.
Definition
Custom events are user-defined events that simulate real events within the context of an application. They allow developers to create events that have business significance within their application, providing a way to handle specific conditions or actions in a decoupled manner.
Creating Custom Events
Custom events are created using the CustomEvent constructor. This constructor allows you to define an event type and pass additional data through the detail property. Once a custom event is created, it can be dispatched using the dispatchEvent method. This process enables the event to be listened to and handled by any part of the application that is interested in that specific event type.
Example: Using Custom Events
The following example demonstrates how to use custom events to simulate an Ajax operation. In this scenario, an animated pinwheel image is displayed while the Ajax operation is underway. The operation is triggered by the click of a button.
Listing 13.10. Using custom events
<style>
#whirlyThing { display: none; }
</style>
<button type="button" id="clickMe">Start</button> #A
<img id="whirlyThing" src="whirly-thing.gif" /> #B
<script>
function triggerEvent(target, eventType, eventDetail){
const event = new CustomEvent(eventType, { #C
detail: eventDetail #D
});
target.dispatchEvent(event); #E
}
function performAjaxOperation() { #F
triggerEvent(document, 'ajax-start', { url: 'my-url'}); #F
setTimeout(() => { #F
triggerEvent(document, 'ajax-complete'); #F
},5000);
}
const button = document.getElementById('clickMe');
button.addEventListener('click', () => {
performAjaxOperation(); #G
});
document.addEventListener('ajax-start', e => { #H
document.getElementById('whirlyThing').style.display = 'inline-block';
assert(e.detail.url === 'my-url', 'We can pass in event data'); #I
});
document.addEventListener('ajax-complete', e => { #J
document.getElementById('whirlyThing').style.display = 'none';
});
</script>
- #A - A button that we’ll click to simulate an Ajax request.
- #B - Our spinner image, which indicates loading, if shown.
- #C - Uses the
CustomEventconstructor to create a new event. - #D - Passes in information to the event object through the
detailproperty. - #E - Uses the built-in
dispatchEventmethod to dispatch the event to the specified element. - #F - Mimics our Ajax request with a timer. At the start of execution, triggers the
ajax-startevent. After enough time elapses, triggers theajax-completeevent. Passes in a URL as additional event data. - #G - When a button is clicked, the Ajax operation is started.
- #H - Handles the
ajax-startevent by showing our whirly thing. - #I - Checks that we can access additional event data.
- #J - Handles the
ajax-completeevent by hiding our whirly thing.
This example illustrates how custom events can be used to manage asynchronous operations in a web application, providing a clear and decoupled way to handle the start and completion of an Ajax request.