调度名称中带有点的 CustomEvent 不会触发 jQuery.on() 事件侦听器
我使用了 jQuery 版本 2.2.4 并尝试捕获事件 - 没有运气。有什么办法可以解决问题吗?
此代码有效:
window.addEventListener('test.namespace', e => console.log('CustomEvent with namespace captured by vanilla'));
这不起作用:
$(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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“普通”DOM 事件系统没有命名空间的概念。
window.addEventListener('test.namespace', ...)
实际上将监听名为test.namespace
的事件,这是您使用 <代码>new CustomEvent('test.namespace', ...).事件命名空间是 jQuery 中的一个概念:
这里重要的是命名空间不是事件名称的一部分。这就是为什么
new CustomEvent('test.namespace', ...)
不起作用,但new CustomEvent('test', ...)
可以。如果你想触发特定命名空间的事件,你必须使用 jQuery:
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 nametest.namespace
, which is what you are creating withnew CustomEvent('test.namespace', ...)
.Event namespaces is a concept in jQuery:
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, butnew CustomEvent('test', ...)
would.If you want to trigger an event for a specific namespace, you have to use jQuery for that:
前面的答案并没有真正解决如何为来自第三方(非 jQuery)库并且事件名称中有一个点的自定义事件注册处理程序的问题。假设该事件是
foo.bar
。简而言之,jQuery 没有办法为此类事件安装处理程序。
$(window).on( 'foo.bar' )
将为事件foo
安装一个处理程序。似乎没有任何方法可以转义名称中的点,或者强制 jQuery 为名为
foo.bar
的事件安装处理程序。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 eventfoo
.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
.