iyel iyel - 6 months ago 29
jQuery Question

Dispatching CustomEvent with dot in name do not trigger jQuery.on() event listener

I've used jQuery version 2.2.4 and tried to capture event - no luck. Is there any way to fix issue?

This code works:

window.addEventListener('test.namespace', e => console.log('CustomEvent with namespace captured by vanilla'));


This does not work:

$(window).on('test.namespace', e => console.log('CustomEvent with namespace captured by jQuery'));

const event = new CustomEvent('test.namespace', {
bubbles: true,
detail: 123
});
window.dispatchEvent(event);


http://jsbin.com/tecupavuji/edit?html,js,console

Answer

The "normal" DOM event system doesn't have a concept of namespaces. window.addEventListener('test.namespace', ...) will literally be listening for an event with the name test.namespace, which is what you are creating with new CustomEvent('test.namespace', ...).

Event namespaces is a concept in jQuery:

An event name can be qualified by event namespaces that simplify removing or triggering the event. For example, "click.myPlugin.simple" defines both the myPlugin and simple namespaces for this particular click event. A click event handler attached via that string could be removed with .off("click.myPlugin") or .off("click.simple") without disturbing other click handlers attached to the elements.

What's important here is that the namespace is not part of the event name. That's why new CustomEvent('test.namespace', ...) doesn't work, but new CustomEvent('test', ...) would.

If you want to trigger an event for a specific namespace, you have to use jQuery for that:

$(window).trigger('test.namespace', {detail: 123});

$(window).on('test.namespace', e => console.log('CustomEvent with namespace captured by jQuery'));

$(window).trigger('test.namespace', {detail: 123});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments