I'm writing a plugin which will eventually be used on different sites. The plugin communicates with the rest of the page on an event basis. So far so good.
Now here is the catch: Some existing sites use pure JS to listen and dispatch events, some use JQuery. The plugin itself should not use jQuery (for different reasons) but only pure JS. So the goal is basically to listen to and dispatch jQuery-like events without jQuery.
How can pure JS Events and jQuery Events work together, especially with custom data attached to the event?
Dispatcher Listener Event Triggered Event Data Transmitted
JS JS yes yes (event.detail)
JS jQuery yes no
jQuery JS no no
jQuery jQuery yes yes (payload)
Here is the codepen: https://codepen.io/st_h_/pen/WNMYPBQ
CodePudding user response:
JQuery has it's own event's layer on top of Vanilla so it's not really possible to catch JQuery events in Vanilla JavaScript.
One option is to use JQuery to listen for and repeat them as normal DOM events, witch is exactly what jquery-events-to-dom-events does.
But then your still using JQuery, kinda...
CodePudding user response:
Thank you for linking a codepen to your code :D
First thing you need to do is "convert" your jQuery element to a "pure JS" one. By doing a .get(0)
, you can now use the dispatchEvent
function with a CustomEvent
we would be making with the input value as the detail
option, it really needs to be detail and not value.
$button.bind("click", () => {
const event = new CustomEvent('update', { detail: $input.val() });
$h1.get(0).dispatchEvent(event);
});
And then the only change you'd need to make to your even listener would be to use detail
property instead of value
.
_h1.addEventListener("update", function(e){
this.innerText = e.detail || "no event.detail"
});