Custom Events in JavaScript

Custom events in JavaScript are user-defined events that provide a mechanism for creating more flexible and decoupled code. They simulate real events within the context of an application, allowing developers to define events that have specific business logic or application-specific meaning.

Overview

Custom events are particularly useful when you want to simulate the experience of a real event for the users of your shared code. They allow you to create events that make sense within the context of your application, rather than relying solely on the standard set of DOM events.

Example: Triggering a Custom Event

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, and 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>

Explanation

  • #A: A button is provided that, when clicked, simulates an Ajax request.
  • #B: An image of a spinner (whirly thing) is used to indicate loading.
  • #C: The CustomEvent constructor is used to create a new event.
  • #D: Information is passed to the event object through the detail property.
  • #E: The dispatchEvent method is used to dispatch the event to the specified element.
  • #F: The Ajax request is mimicked with a timer. The ajax-start event is triggered at the start, and the ajax-complete event is triggered after a delay. Additional event data, such as a URL, is passed.
  • #G: When the button is clicked, the Ajax operation is initiated.
  • #H: The ajax-start event is handled by displaying the spinner.
  • #I: The additional event data is accessed and verified.
  • #J: The ajax-complete event is handled by hiding the spinner.

This example illustrates how custom events can be used to manage application-specific logic in a clean and decoupled manner, enhancing the flexibility and maintainability of the code.