Skip to content

Instantly share code, notes, and snippets.

@jherax
Last active October 25, 2023 02:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jherax/968ad4ff8eaa9ceb9159 to your computer and use it in GitHub Desktop.
Save jherax/968ad4ff8eaa9ceb9159 to your computer and use it in GitHub Desktop.
jQuery: Gets all event handlers bound to a DOM Element
/**
* 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;
}
// 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')
@jherax
Copy link
Author

jherax commented Jun 12, 2015

Aprende más sobre los namespaced-events en jQuery, ya que es una buena práctica que te permitirá tener un mayor control de los event listeners que registramos, pudiendo así evitar fugas de memoria y prevenir reprocesamiento lo que se traduce en una mejora del performance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment