Forked from kaspermeyer/jquery_event_delegator.coffee
Created
October 23, 2024 15:53
-
-
Save marcosgz/6224ed02c505eca0cabc18121738305c to your computer and use it in GitHub Desktop.
Dispatch jQuery events as regular DOM events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ~ Dispatch jQuery events as regular DOM events ~ | |
# | |
# Delegated events are given a new name in the format `jquery:<original event name>`. | |
# If you delegate `ajax:send` you will be able to listen for `jquery:ajax:send` | |
# on native event listeners such as Stimulus actions and `EventTarget.addEventListener`. | |
# | |
# Notes: | |
# * The first parameter must be called "event". | |
# * The parameters can be accessed as members on the `event.detail` object. | |
# | |
# Example: | |
# delegate 'ajax:send', parameters: ['event', 'xhr'] | |
# document.addEventListener 'jquery:ajax:send', (event) -> console.log(event.detail) | |
# | |
delegate = (eventName, {parameters}) -> | |
handler = (args...) -> | |
data = {} | |
data[name] = args[index] for name, index in parameters | |
delegatedEvent = new CustomEvent("jquery:#{eventName}", | |
bubbles: true, | |
cancelable: true, | |
detail: data) | |
data.event.target.dispatchEvent(delegatedEvent) | |
$(document).on(eventName, handler) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment