Friday, June 27, 2014

Did you Know That... an event handler will execute in JavaScript as many times as registered when the event is triggered. How to disallow that?

Recently I have been looking at JavaScript files written by, perhaps, less experienced JavaScript developers and noticed that  in some instances the code was calling a function which was manually wiring an event and that this function was being called more than once.

The problem with this is that the event handler will be executed as many times as the event was registered and this could have a performance impact or have other unwanted consequences.  So, how to stop registering events in JavaScript more than once?  Being "careful" might work for small projects but code can grow very quickly and it is just as easy to register the event again.

This note is trying to explore different ways or techniques to avoid registering an event more than once and therefore avoid the negative consequences that might bring the execution of the event handler multiple times.

UnBind and Bind Event

The easiest way to prevent an event from being wired to an element more than once would be to unbind all bound events and bind the event again.  This technique would work well.  I often yank code like that into a common area where it could be reused from anywhere in the code.


Figure 1: Line 8 unbinds all click events and binds a single one. Line 7 is only there fore sanity just in case that the callback handler is not a function


Tests for Registered Events

A different way of accomplishing the same result would be to test if the event has been already bound to the element. In the case that the event has already been bound then the event is not manually bound.


Figure 2: The event is registered if and only if not registered previously. This variant is a bit more involved and it is essentially different from what was presented in Figure 1.

None of this is new, as a matter of fact the above techniques can be found all over the internet.  The important issue here is that one has to be careful when binding events manually.  Multiple binding could be the cause of unnecessary server posts taxing in performance and unexpected results.

However, the above techniques would be useless if the team does not adopt them at large and the code is littered with event bindings indiscriminately.  But always keep in mind that "If the Scatman can do it, so can you".


No comments:

Post a Comment

A1 Repo: Simple Pagination for WCF Service Operation

It is never a good idea to paginate on the client.  This post is about a simple pagination for a WCF service operation.  For this work I nee...