Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get jQuery to trigger a native custom event handler

Tags:

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 live example

Edited to add:

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.

like image 327
Stephen Thomas Avatar asked Apr 28 '16 12:04

Stephen Thomas


1 Answers

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()`
}

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.

like image 75
Stephen Thomas Avatar answered Sep 28 '22 01:09

Stephen Thomas