Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm triggering some DOM Events with jQuery 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
313 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you want an exact replication of jQuery's behaviour, you're probably best off digging through the jQuery source code.

If you just want to do normal event dispatching and listening, see CustomEvent for how to dispatch an event with custom data and addEventListener for how to listen to it.

Your example would probably look something like

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...