Consider this:
var fn = function() { console.log("hi") };
$(document).keydown(fn);
$(document).keydown(fn);
fn
will be fired two times when I press key inside document.
Is there a way to add event uniquely without need to unbind it first?
Consider this:
var fn = function() { console.log("hi") };
$(document).keydown(fn);
$(document).keydown(fn);
fn
will be fired two times when I press key inside document.
Is there a way to add event uniquely without need to unbind it first?
There is a way, and it is by setting the .onkeydown
property of the DOM element with a function (not using jQuery at all). Since assigning it will overwrite what was there previously, it will not chain.
Of course being able to chain is clearly more powerful and that is the power that jQuery gives you.
It is likely that calling unbind is the correct solution, but just for completeness, setting the .on[eventname]
prop will work well for when you know there is only one function you want to trigger.
No. You're best bet is to unbind first. You could also manually check which handlers are bound to an object before binding if you want to do it that way. See: jQuery find events handlers registered with an object