最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - trigger custom event without jQuery - Stack Overflow

programmeradmin2浏览0评论

I'm triggering some DOM Events with jQuery triggerHandler()

<!DOCTYPE html>
<html>
<head>
  <title>stackoverflow</title>
  <script src=":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>

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>

How can I trigger this without jQuery?

Important: I need to know the event type and the custom data

Share Improve this question edited Apr 27, 2015 at 14:20 Liam 29.7k28 gold badges137 silver badges200 bronze badges asked Apr 27, 2015 at 14:16 Christian HallerChristian Haller 6631 gold badge8 silver badges17 bronze badges 3
  • 1 Under the covers jQuery will be using document.addEventListener('hey', function() { ... }); where hey is click, mousedown etc. Is that what you mean? – garryp Commented Apr 27, 2015 at 14:19
  • Reading the jQuery source would show you how it's done, since jQuery is JavaScript. – Sterling Archer Commented Apr 27, 2015 at 14:22
  • As far as i remember, jquery combines .dispatchEvent and .fireEvent for triggerHandler. You can easily write a function to try one or the other. dispatch event will work on most browsers. – David Commented Apr 27, 2015 at 14:35
Add a comment  | 

2 Answers 2

Reset to default 16

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'}}));

You can use Custom Events and dispatch them on element you want.

发布评论

评论列表(0)

  1. 暂无评论