Skip to content

Instantly share code, notes, and snippets.

@lekman lekman/attach.js

Created Apr 22, 2020
Embed
What would you like to do?
/**
* 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
You can’t perform that action at this time.