Plug-in: Ensure Single Event Handler in jQuery

Tobias Lekman
Development

I recently had a performance issue when an AJAX control updated the DOM and the script added event bindings to the elements. However, some elements were unchanged. The events were still added again, causing multiple events and performance degradation within the browser. The existing fix was:

Sure, you can do that. An easier way is to ensure that all current events are removed on the element and then adding it again. This can be done my easier by using ‘off’ as:

Here is a JS fiddle sample of how this works

This works with “element.click” and “element.on(‘click’)” style event handlers, and you can either specify “off” to destroy all events or “off(‘click’)” for a specific event.

Note that you obviously might end up destroying click events added by other code/team members etc, so needs testing and be sure to investigate the events via developer tools or web inspector.

As an update, I wrote a plug-in to handle this as well. The point is, you could use off and on -but what if there are several handlers? You will risk overwriting other events on the item.

For example:

This could cause issues when several events are attached to the same object. So instead, we use this:

The “attach” method is my custom plugin. It will search for the event handler and only add it if not already attached. It works like this:

The point is to interrogate each event of all properties, which is done by iteration as:

We now have event which has info on what type of event it is and what handler is on it. We can interrogate one or both. The handler will be textually the same but can change during browser attachments, so I compare them as string literals, as:

The whole plugin can be downloaded from a Gist on Github.