javascriptcustom-events

javascript custom event losing value after adding a listener


I'm creating a custom logout event, but after the event handler is assigned, the variable that holds the newly created event loses its value.

Here is the code:

<script>
  //
  // Prevent the creation and handler assignment of the login custom event
  // from happening more than once.
  //

  if( typeof( logoutCustomEvent ) === 'undefined' ) {

    // Create the custom logout event ...

    const logoutCustomEvent = new Event( 'logoutCustomEvent' );

    // At this point logoutCustomEvent has the right event object value.

    // Assign a listen handler function to the logout custom event ...

    window
    .addEventListener(
       'logoutCustomEvent',
       ( event ) => { if( event ) alert( 'logout custom event fired!' ); },
       false );

  } // End of if( typeof( logoutCustomEvent ) === 'undefined' ) ...

  // Test the logout custom event ...

  window.dispatchEvent( logoutCustomEvent ); // Dispatch the event.
</script>

When the window.dispatchEvent( logoutCustomEvent ) statement at the end of the code block, above, executes, the following is displayed in the Chrome browser's console:

home:1334 Uncaught ReferenceError: logoutCustomEvent is not defined
at home:1334

However, if I set a breakpoint at the first line of the code shown above, and then monitor the value of the logoutCustomEvent constant, I can see that an event object is assigned by the new statement, but after the addEventListener statement, logoutCustomEvent value is 'not available' in the browser's watch panel.

My code is based on the example shown on the MDN .dispatchEvent page.

Why is this happening, and what do I need to do to prevent this?


Solution

  • const and let define variables only in the current (and nested) code blocks. You cannot access them outside the code block they are declared.
    There are 2 possible solutions:

    1. Use var

    if (typeof(logoutCustomEvent) === 'undefined') {
      var logoutCustomEvent = new Event('logoutCustomEvent');
      window.addEventListener(
        'logoutCustomEvent',
        (event) => {
          if (event) alert('logout custom event fired!');
        },
        false);
    }
    window.dispatchEvent(logoutCustomEvent);
    

    2. Declare logoutCustomEvent outside the if statement

    let logoutCustomEvent;
    if (typeof(logoutCustomEvent) === 'undefined') {
      logoutCustomEvent = new Event('logoutCustomEvent');
      window.addEventListener(
        'logoutCustomEvent',
        (event) => {
          if (event) alert('logout custom event fired!');
        },
        false);
    }
    window.dispatchEvent(logoutCustomEvent);