Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dispatchEvent not triggering jQuery.on() event listener

I have the following code that triggers a custom named event:

elem.addEventListener('click', function (event)
{
    event.preventDefault();

    // Do some processing stuff

    var event = new Event('custom_event');
    this.dispatchEvent(event);
});

If I try to catch the custom event with jQuery.on() it works, but only when I'm not using the descendant selector filter.

So this works:

$('selector').on('custom_event', function () { // works });

But this doesn't:

$(document).on('custom_event', 'selector', function () { // doesn't work });

Can anyone shed some light on why that is? Here's a Fiddle showing the problem.

like image 672
Bogdan Avatar asked Oct 17 '14 11:10

Bogdan


1 Answers

By default the event does not bubble, so when you create an event you need to pass bubbles: true as an option to indicate that you want the event to be bubbled. You can use CustomEvent to do that.

You are using event delegation to register the second handler which makes use of event bubbling to work.

document.querySelectorAll('.button')[0].addEventListener('click', function(e) {
  var event = new CustomEvent('custom_event', {
    bubbles: true
  });
  this.dispatchEvent(event);
});

$(document).on('custom_event', '.button', function() {
  alert('Custom event captured [selector filter]');
});

$('.button').on('custom_event', function() {
  alert('Custom event captured');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="button">Click Me</button>
like image 69
Arun P Johny Avatar answered Oct 10 '22 04:10

Arun P Johny