问题描述
我正在创建自定义注销事件,但在分配事件处理程序后,保存新创建事件的变量将失去其值。
代码如下:
<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 常量的值,我可以看到 {{ 1}} 语句,但在 new
语句之后,logoutCustomEvent 值在浏览器的监视面板中为“不可用”。
我的代码基于 MDN .dispatchEvent page 上显示的示例。
为什么会发生这种情况,我需要做些什么来防止这种情况发生?
解决方法
const
和 let
仅在当前(和嵌套)代码块中定义变量。您不能在它们声明的代码块之外访问它们。
有两种可能的解决方案:
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',false);
}
window.dispatchEvent(logoutCustomEvent);