Binding and Unbinding Events in Real Time

By May 16, 2014Blog

You will often come across a situation where you are setting up some kind of event that is dependent on the document or window for interaction. Typically we don’t want to setup too many event handlers here as they tend to collide with one another, not to mention we don’t need events there constantly running in the background. The quick and usual solution I see is to just wrap some kind of if statement around the event.

$(document).click(function () {
  if (popupShowing) {

This is all fine and good and probably what your code looks like. But what if we were to register this on multiple elements. We will have a bunch of these if statements running on every click. The solution for situations like these is to load and unload the event on the fly.

So in you’re plugin you will have some code that performs some action like opening a modal or popup. In this opening event we would create the “close” handler.

  show: function () {
    // Some code to position and show popup
    // Create close/hide handler in real time.
    $(document).bind('', hide);

  hide: function () {

In the above example we will see or bind and unbind events for the document object. All we do is name the events so that when we hide the popup we unbind the event from the document and keep it clear from listeners.

The document is the easiest example but you will come across these situations often so it’s a good thing to be aware of to avoid polluting your elements with too many events.