Tuesday, October 20, 2015

JavaScript: JQuery Event Binding Tip

Originally published 

Tue 9 Dec 2008

Editors Notes
Many of the tips I had in my original blog were the sort that I discovered through trial and error and quickly posted for safekeeping, such as this item which did in fact take me some time to figure out.

Original Post

I've been using JQuery a LOT at work lately and loving it. It lives up to its promise to allow you to do more and write less code. Presently I'm working on a totally dynamic interface using JQuery a lot. I discovered an interesting thing with Event binding though worth noting.

When you bind an event, it's like writing the Javascript directly into the HTML. For example, $('#somediv').click puts your function in the OnClick event for the target element. What I found was that this is an append, not an overwrite by default. So if I call a function that performs the Event binding more than once, my function is now 'bound' multiple times, which would cause my OnClick event to fire the target function multiple times, likely or possibly with unintended consequences.
To prevent this from happening, just call .unbind before you bind.

$('#somediv').click(function() {stuff;});

After that, the function is only bound a single time each time, not cumulatively. You can imagine that took more than a couple of minutes to figure out!

Editors further note...
It's far safer to bind events to the top level container, one time, at startup.  All events bubble up to the top level container*.  (* usually).

No comments:

Post a Comment