Created
December 13, 2018 14:06
-
-
Save kaspermeyer/7fe28bb7c55c2810e7b5f3d5e67c1a44 to your computer and use it in GitHub Desktop.
Dispatch jQuery events as regular DOM events
This file contains hidden or 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
I wish I'd seen this thread a long time ago!
I ended up creating jquery-events-to-dom-events to handle this problem in a way that would drop right into Stimulus controllers.