不使用jQuery触发自定义事件

Chr*_*ler 16 javascript jquery dom-events jquery-triggerhandler

我用jQuery触发了一些DOM事件 triggerHandler()

<!DOCTYPE html>
<html>
<head>
  <title>stackoverflow</title>
  <script src="http://ajax.googleapis.com:80/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

<body>
  <script>
    $(document).ready(function() {
      $(document).on('hey', function(customEvent, originalEvent, data) {
        console.log(customEvent.type + ' ' + data.user); // hey stackoverflow

      });

      // how to this in vanilla js
      $(document).triggerHandler('hey', [{}, {
        'user': 'stackoverflow'
      }])
    });
  </script>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)

如何在没有jQuery的情况下触发这个?

重要提示:我需要知道事件类型和自定义数据

Sig*_*uza 15

如果你想要精确复制jQuery的行为,你可能最好挖掘一下jQuery source code.

如果您只想进行正常的事件调度和侦听,请参阅CustomEvent如何使用自定义数据调度事件以及addEventListener如何侦听它.

你的例子可能看起来像

document.addEventListener('hey', function(customEvent)
{
    console.log(customEvent.type + ' ' + customEvent.detail.user); // hey stackoverflow
});
document.dispatchEvent(new CustomEvent('hey', {'detail': {'user': 'stackoverflow'}}));
Run Code Online (Sandbox Code Playgroud)

  • `CustomEvent`构造函数在IE中没有支持. (4认同)
  • @Johnston但看起来有一个[polyfill for it](https://github.com/krambuhl/custom-event-polyfill/blob/master/custom-event-polyfill.js). (3认同)