Listen to jQuery event without jQuery

拟墨画扇 提交于 2019-12-23 08:29:12

问题


Is there a way to set up an event listener, so it captures an event fired by jQuery? I want to use only plain (vanilla) JavaScript to listen to the event.

I have set up the following example:

(function($) {

    $(document).on('sent_jquery_rec_jquery', function () {
        console.log('sent_jquery_rec_jquery');
    });

    $(document).on('sent_vanilla_rec_jquery', function () {
        console.log('sent_vanilla_rec_jquery');
    });

    document.addEventListener('sent_vanilla_rec_vanilla', function () {
        console.log('sent_vanilla_rec_vanilla');
    });

    document.addEventListener('sent_jquery_rec_vanilla', function () {
        console.log('sent_jquery_rec_vanilla');
    });

    document.dispatchEvent(new Event("sent_vanilla_rec_vanilla"));
    document.dispatchEvent(new Event("sent_vanilla_rec_jquery"));

    $(document).trigger('sent_jquery_rec_jquery');
    $(document).trigger('sent_jquery_rec_vanilla');

}(jQuery));

Three events which are received and logged are:

  • sent_vanilla_rec_vanilla
  • sent_vanilla_rec_jquery
  • sent_jquery_rec_jquery

When the event is sent via $(document).trigger, the event listener set up with document.addEventListener does not kick in. What's the reason for that, and how can I make it work?


回答1:


JQuery apparently uses a custom event system, so you can't listen to jQuery events with a regular event listener. The aforementioned ticket mentions IE <9 as the culprit here, maybe jQuery 3 or 4 could make the switch.



来源:https://stackoverflow.com/questions/32502713/listen-to-jquery-event-without-jquery

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