DispatchEvent does not start jQuery.on () event listener
I have the following code that fires 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 a custom event using jQuery.on () it works, but only when I don't use the descendant selector filter.
So this works:
$('selector').on('custom_event', function () { // works });
But this is not the case:
$(document).on('custom_event', 'selector', function () { // doesn't work });
Can anyone shed some light on what this is? Here Fiddle shows the problem.
+3
source to share
1 answer
By default, the event does not bubble, so when you create the event, you need to pass bubbles: true
as an option to indicate that you want the event to bubble. You can use CustomEvent to do this.
You use event delegation to register a second handler that uses event bubbles.
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>
+11
source to share