With AJAX and DOM nodes being injected into HTML all the time these days, there's probably a good chance that your web application requires re-binding events on new nodes that are created on the fly. If you're not careful and you write some function that re-applies the event associations to all classes rather than the new node, you might end up over-binding your events (i.e. the same event is now associated with that element multiple times). That's obvious not good and will eventually cause horrible performance issues on the browser as you accumulate unnecessary levels of events.
jQuery provides an excellent solution with the live function. The live function simply allows the event to be bound to an element when you expect some dynamic behavior. The usage is fairly simply to implement and allows for easy modification of existing code:
$('.my_class').live('click', function(){ // do something // }
Here, we simply bind the "click" event to all 'my_class' classes. So if I were to create a new node that requires a special activity to be generated during a click event, I do not need anything more than that little additional bit of code.
I don't know what the memory/performance implications of adding the live function to every event. However, I do expect that you should only use it for the case of dynamic nodes. So if you do not expect this behavior, don't start converting all your event bindings to the live function.
The reason why I'm writing this up is that previously I would create a function so that during the DOM injection (i.e. $('#some_node').html(data.html);), I would call that function to reapply my event bindings. Eventually, that led to overly complicated code and even browser side performance issues and redundant responses from events that I had bound. Hopefully, people reading this article who encounter a similar issue can utilize this technique to make their lives slightly easier.
Trackbacks: (Trackback URL)