js 自定义事件 CustomEvent

795 阅读1分钟

坑: 事件参数要用 detail, 不然挂在不上去。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    const TEST_EVENT = 'test-event'
    let testEvent = new CustomEvent(TEST_EVENT,{
      detail: {
        aaaaa: 'props'
      }
    })
    window.addEventListener(TEST_EVENT, (prop) => {
      console.log(prop);
      console.log(prop.detail);
    })
    
    setTimeout(() => {
      window.dispatchEvent(testEvent)
    }, 100);

  </script>
</body>
</html>

developer.mozilla.org/zh-CN/docs/…