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
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>
The previous answer doesn't really address the problem of how to register a handler for a custom event which comes from a third-party (non-jQuery) library and which has a dot in the event name. Say the event is foo.bar
.
The short answer is that jQuery doesn't have a way to install a handler for such an event.
$(window).on( 'foo.bar' )
will instead install a handler for the event foo
.
There doesn't seem to be any way to escape the dot in the name or otherwise coerce jQuery into installing a handler for an event named foo.bar
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With