javascript 添加侦听器后自定义事件失去价值

javascript custom event losing value after adding a listener

我正在创建一个自定义注销事件,但在分配事件处理程序后,保存新创建的事件的变量失去了它的值。

代码如下:

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

当上述代码块末尾的 window.dispatchEvent( logoutCustomEvent ) 语句执行时,Chrome 浏览器的控制台中显示以下内容:

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

但是,如果我在上面显示的代码的第一行设置一个断点,然后监视 logoutCustomEvent 常量的值,我可以看到一个事件对象是由 new 语句分配,但在 addEventListener 语句之后,logoutCustomEvent 值在浏览器的监视面板中为 'not available'。

我的代码基于 MDN .dispatchEvent page.

上显示的示例

为什么会发生这种情况,我需要做什么来防止这种情况发生?

constlet 仅在当前(和嵌套)代码块中定义变量。您无法在声明的代码块之外访问它们。
有 2 种可能的解决方案:

1。使用 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。在 if 语句

之外声明 logoutCustomEvent
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);