I want some way to add and remove unique, named events to elements so I can make sure the event is never added more than once. When you add events to an element, they get stacked on each other, even if two of them are meant to be the same event. For a simple -but abstracted- example:
$('a').on("click", function(e){ console.log("Hi One"); }); // 1
$('a').on("click", function(e){ console.log("Hi One"); }); // duplicate
$('a').on("click", function(e){ console.log("Hi Two"); }); // 2
// Output will be: Hi One, Hi One, Hi Two
I tried using a method like .off().on(), but that only allows for one event at a time.
$('a').off("click").on("click", function(e){ console.log("Hi One"); });
$('a').off("click").on("click", function(e){ console.log("Hi One"); });
$('a').off("click").on("click", function(e){ console.log("Hi Two"); });
// Output will be: Hi Two
So I came up with this extension for jQuery:
$.fn.onUnique = function (
/* uniqueEventName, events [,selector] [,data], handler(eventObject) */
) {
var uniqueEventNameArray = this.data("uniqueEvents") || [];
var uniqueEventName = arguments[0];
if ($.inArray(uniqueEventName, uniqueEventNameArray) == -1) {
uniqueEventNameArray.push(uniqueEventName);
this.data("uniqueEvents", uniqueEventNameArray);
this.on(arguments[1], arguments[2], arguments[3], arguments[4]);
}
};
So I can get the effect I want…
$('a').onUnique("Hi1", "click", function(e){ console.log("Hi One"); });
$('a').onUnique("Hi1", "click", function(e){ console.log("Hi One"); });
$('a').onUnique("Hi2", "click", function(e){ console.log("Hi Two"); });
// Output will be: Hi One, Hi Two
My questions are two:
- Is there a better way to do this?
- How would I do the equivalent of .offUnique(), which would remove only the specified event (by name)?
Check out the namespaced events :
event.namespaceDemo http://jsfiddle.net/gaby/378rP/
You should probably, though, try to organize your code better so you do not apply the same event twice..