如何让jQuery触发本机自定义事件处理程序 [英] How to get jQuery to trigger a native custom event handler

查看:67
本文介绍了如何让jQuery触发本机自定义事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道获取jQuery .trigger()所需的魔力来触发由(不是jQuery )本机处理的自定义事件JavaScript事件处理程序?

Does anyone know the magic required to get jQuery .trigger() to trigger a custom event that's handled by a (not jQuery) native JavaScript event handler?

test = document.querySelectorAll('.test')[0];
test.addEventListener('click', function() {
    console.log('click')
});
test.addEventListener('custom', function(ev) {
    console.log('custom', ev.detail)
});

// Custom Native -> Native works as expected
test.dispatchEvent(new CustomEvent('custom', {detail: 'detail'})); // -> "custom" "detail"

// Standard jQuery -> Native works as expected
$(test).trigger('click'); // -> "click"

// Custom jQuery -> Native does not work
$(test).trigger('custom'); // -> No log?
$(test).trigger({type: 'custom'}); // -> No log?

codepen.io实时示例

编辑添加:

关于我的用例的更多细节。我正在开发一个依赖于自定义事件的库,但它本身并不使用jQuery。但是,我想使这个库很方便那些有jQuery的应用程序。

A bit more details on my use case. I'm developing a library that relies on custom events but doesn't itself use jQuery. However, I'd like to make the library convenient for those applications that do have jQuery.

推荐答案

勉强进入调试器中的jQuery源代码,看起来有一个解决方案。不优雅,但可行。诀窍是在元素中添加 onxxxx 属性,其中 xxxx 是事件名称。问题中代码的添加将是:

Well, after stepping through the jQuery source in a debugger, it looks like there is a solution. Not elegant, but workable. The trick is to add an onxxxx property to the element, where xxxx is the event name. The addition to the code in the question would be:

test.oncustom = function(ev, data) {
    // ev is the jQuery Event object
    // data is data passed to jQuery `.trigger()`
}

请注意,jQuery不会将自定义数据添加到例如 ev.detail ,就像标准事件的情况一样。相反,它将自定义数据作为附加参数传递。

Note that jQuery does not add custom data to, for example, ev.detail, as would be the case for a standard event. Instead it passes custom data as an additional parameter.

这篇关于如何让jQuery触发本机自定义事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆