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