You can use this jQuery extension function.
$.fn.once = function (type, fn, uid) { if(uid == undefined) { console.error("Called $.once without uid\n", this, "\n", fn); } var dataStr = type+"-handler-"+uid; if(!this.data(dataStr)) { this.data(dataStr, true); this.on(type, fn); } };
Instead of this
$("button").on("click", function(){ alert("You Clicked On A Button"); });
I'm doing it
$("button").once("click", function(){ alert("You Clicked On A Button"); }, "btnHandler");
Now that I have a function around her
function addBtnHandler() { $("button").once("click", function() { alert("You Clicked On A Button"); }, "btnHandler"); }
And I call it a few times
addBtnHandler(); addBtnHandler(); addBtnHandler();
He does this only once.
Note that the extension works by checking both the uid and type. This means that you can bind different types of handlers with the same uid, you may or may not want this. To change it, edit.
var dataStr = type+"-handler-"+uid;
With something like
var dataStr = "handler-"+uid;
nathnolt Feb 06 '17 at 9:17 2017-02-06 09:17
source share