-
-
Save syed-ahmad/d3d62bc3f51390a07e7b8354aa912d78 to your computer and use it in GitHub Desktop.
jQuery: Gets all event handlers bound to a DOM Element
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
/** | |
* Gets all event-handlers from a DOM element. | |
* Events with namespace are allowed. | |
* | |
* @param {Element} node: DOM element | |
* @param {String} eventns: (optional) name of the event/namespace | |
* @return {Object} | |
*/ | |
function getEventHandlers(element, eventns) { | |
const $ = window.jQuery; | |
const i = (eventns || '').indexOf('.'), | |
event = i > -1 ? eventns.substr(0, i) : eventns, | |
namespace = i > -1 ? eventns.substr(i + 1) : void(0), | |
handlers = Object.create(null); | |
element = $(element); | |
if (!element.length) return handlers; | |
// gets the events associated to a DOM element | |
const listeners = $._data(element.get(0), "events") || handlers; | |
const events = event ? [event] : Object.keys(listeners); | |
if (!eventns) return listeners; // Object with all event types | |
events.forEach((type) => { | |
// gets event-handlers by event-type or namespace | |
(listeners[type] || []).forEach(getHandlers, type); | |
}); | |
// eslint-disable-next-line | |
function getHandlers(e) { | |
const type = this.toString(); | |
const eNamespace = e.namespace || (e.data && e.data.handler); | |
// gets event-handlers by event-type or namespace | |
if ((event === type && !namespace) || | |
(eNamespace === namespace && !event) || | |
(eNamespace === namespace && event === type)) { | |
handlers[type] = handlers[type] || []; | |
handlers[type].push(e); | |
} | |
} | |
return handlers; | |
} |
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
// get all event handlers bound to the DOMElement | |
getEventHandlers(document); | |
// get all "click" event handlers bound to the DOMElement | |
getEventHandlers("#my-form", "submit"); | |
// getall "click" event handlers having the namespace ".cbox" | |
getEventHandlers(document, 'click.cbox') | |
// get all event handlers with the namespace ".cbox" | |
getEventHandlers(document, '.cbox') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment