Skip to content

Instantly share code, notes, and snippets.

@lekman
Created April 22, 2020 09:15
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 lekman/d17d54e1a359bf897ab178b21de2bf84 to your computer and use it in GitHub Desktop.
Save lekman/d17d54e1a359bf897ab178b21de2bf84 to your computer and use it in GitHub Desktop.
/**
* Custom plugin to find if an object already has an event handler and also to attach
* event handlers only if not already attached.
*/
(function ($) {
/**
* Attaches an event handler only if not already attached.
* @param {any} type The event type, such as 'click' or 'keyup'.
* @param {any} handler The function handler.
*/
$.fn.attach = function (type, handler) {
// Only attach if not already on element
if (!$(this).isAttached(type, handler)) {
$(this).on(type, handler);
}
};
/**
* Determines if a handler is attached for an event on an element.
* @param {any} type The event type, such as 'click' or 'keyup'.
* @param {any} handler The function handler.
*/
$.fn.isAttached = function (type, handler) {
var found = false;
this.each(function () {
var events = $._data($(this)[0], "events");
for (var prop in events) {
if (Object.prototype.hasOwnProperty.call(events, prop)) {
var event = events[prop][0];
if (event.type === type && typeof (handler) === "undefined") {
// The event type, such as 'keyup' is attached but we are not
// comparing the function. The event is attached.
found = true;
}
if (event.type === type && typeof (handler) !== "undefined") {
// Compare the function
var comparer = event.handler.toString().replace(/\s/g, "") === handler.toString().replace(/\s/g, "");
// We compare on function level as well
// and they are the same. The event is attached.
if (comparer) {
found = true;
}
}
}
}
});
// The event was not found
return found;
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment