Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save marcosgz/6224ed02c505eca0cabc18121738305c to your computer and use it in GitHub Desktop.
Save marcosgz/6224ed02c505eca0cabc18121738305c to your computer and use it in GitHub Desktop.
Dispatch jQuery events as regular DOM events
# ~ 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