trigger custom event without jQuery

白昼怎懂夜的黑 提交于 2019-11-27 17:30:48

问题


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


回答1:


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



回答2:


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




回答3:


The quick & easy way:

$('#element').trigger("mycustomevent");

or for global event:

$(document).trigger("mycustomevent");

catching it:

$('#element').on("mycustomevent", function(e){
    // do something
});


来源:https://stackoverflow.com/questions/29898254/trigger-custom-event-without-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!