Custom Events

Frontend SELF EN
Level 42 , Lesson 2
Available

8.1 Creating Custom Events

Custom events (or user-defined events) in JavaScript let developers create and dispatch their own events. This can be super handy for passing info and interacting between different parts of an app. Creating and using custom events can enhance the structure and flexibility of your code by giving you a way to notify and manage the app's state.

To create custom events, you use the CustomEvent constructor. This constructor lets you create new events with customizable parameters and additional data.

Syntax:

    
      const event = new CustomEvent(type, {detail: additionalData});
    
  

Where:

  • type: a string representing the event name
  • detail: an object containing additional data to be passed with the event

Example of creating a custom event:

JavaScript
    
      const myEvent = new CustomEvent('myCustomEvent', { detail: { message: 'Hello, world!' } });
    
  

8.2 Dispatching Custom Events

Dispatching an event is done with the dispatchEvent method. This method is called on the element where the event is supposed to happen.

Explanation:

  • A handler for the myCustomEvent is added to the button myButton, which logs the event data's message to the console
  • A custom event myCustomEvent is created with a message in detail
  • The event is dispatched on the button myButton, triggering the handler and logging the message to the console

Example:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Custom Event Example</title>
        </head>
        <body>
          <button id="myButton">Button</button>
          <script>
            const button = document.getElementById('myButton');

            // Adding a handler for the custom event
            button.addEventListener('myCustomEvent', function(event) {
              console.log('Custom event received:', event.detail.message);
            });

            // Creating and dispatching the custom event
            const myEvent = new CustomEvent('myCustomEvent', { detail: { message: 'Hello, world!' } });
            button.dispatchEvent(myEvent);
          </script>
        </body>
      </html>
    
  

8.3 Applying Custom Events

Custom events are useful for building more modular and maintainable code, especially when dealing with components and complex apps. They allow one component to notify other components of changes or actions that have occurred.

Explanation:

  • Module A dispatches a custom event notifyB on the element moduleB, passing data
  • Module B listens for the notifyB event and processes it, logging the message to the console

Example of using custom events in a modular app:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Module Communication Example</title>
        </head>
        <body>
          <div id="moduleA">Module A</div>
          <div id="moduleB">Module B</div>
          <script>
            const moduleA = document.getElementById('moduleA');
            const moduleB = document.getElementById('moduleB');

            // Module A dispatches a custom event
            function notifyModuleB() {
              const event = new CustomEvent('notifyB', { detail: { message: 'Data from Module A' } });
              moduleB.dispatchEvent(event);
            }

            // Module B listens for the custom event
            moduleB.addEventListener('notifyB', function(event) {
              console.log('Module B received:', event.detail.message);
            });

            // Simulate an action in Module A
            notifyModuleB();
          </script>
        </body>
      </html>
    
  

8.4 Custom Event Parameters

Custom events can be further customized using the following parameters:

  • bubbles: a boolean indicating whether the event should bubble. Defaults to false
  • cancelable: a boolean indicating whether the event can be canceled. Defaults to false
  • composed: a boolean indicating whether the event should propagate outside of shadow DOM trees. Defaults to false

Example:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Custom Event Parameters Example</title>
        </head>
        <body>
          <div id="container">
            <button id="myButton">Button</button>
          </div>
          <script>
            const container = document.getElementById('container');
            const button = document.getElementById('myButton');

            // Adding listeners for the container and button
            container.addEventListener('customEvent', function(event) {
              console.log('Container received:', event.detail.message);
            });

            button.addEventListener('customEvent', function(event) {
              console.log('Button received:', event.detail.message);
            });

            // Creating and dispatching the custom event with parameters
            const myEvent = new CustomEvent('customEvent', {
              detail: { message: 'Hello from button' },
              bubbles: true,
              cancelable: true,
              composed: false
            });

            button.dispatchEvent(myEvent);
          </script>
        </body>
      </html>
    
  
1
Task
Frontend SELF EN, level 42, lesson 2
Locked
Save Notification
Save Notification
1
Task
Frontend SELF EN, level 42, lesson 2
Locked
Text Update
Text Update
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION