ENsuring Single Instance Of Event Handlers

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 and the events were still added again, causing multiple events and performance degradation within the browser. The existing fix was:

if (!$("#open-btn").hasClass("init")) {
	$("#open-btn").click(open);
  $("#open-btn").addClass("init");
}

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:

$("#open-btn").off().click(open);

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 devtools or web inspector.