Skip to content

Instantly share code, notes, and snippets.

@FunnyDewd
Created August 29, 2013 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FunnyDewd/6372956 to your computer and use it in GitHub Desktop.
Save FunnyDewd/6372956 to your computer and use it in GitHub Desktop.
Here's a function which will check jQuery whether a particular element has a namespaced (which is always a good idea) event handler attached to it. It returns true if one exists, false otherwise. Example: checkForHandler("body", "click.foo"); // checks the body element for a click.foo handler
// function: checkForHandler(elem, event)
// - Checks whether the elem has a handler for the namespaced event
// returns: bool - true if the event handler exists, false otherwise
// params: elem - element to query (either dom element or jquery object)
// event - string with the type of element with namespace (click.foo)
var checkForHandler = function(elem, event) {
if ((typeof elem === "undefined") || (typeof event === "undefined")) {
// really?? Y U No Pass Arguments?
return false;
}
// ensure we have a DOM element, not a jQuery obj.
var theElem = $(elem).get(0);
var eventType = event.split('.')[0];
var namespace = event.split('.')[1];
if($.hasData(theElem)){
var jQEvents = $._data(theElem, "events")[eventType];
if (!jQEvents) { // There are no events of type eventType
return false;
} else {
if (namespace) {
for (var i = 0; i < jQEvents.length; i++) {
if (jQEvents[i].namespace === namespace) {
return true;
}
}
// couldn't find it, return false
return false;
}
}
} else {
// there's nothing attached to this element
return false;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment