Event binding with Delegated Events & Async Dom Manipulation

In the olden days of jQuery there were a myriad of ways to bind events in the DOM. You had to take into account things like, is the element always present when the page loads, are things going to be added to the DOM dynamically, and so on. With those things to consider you had tons of options for binding events. There was:

  • .click() : for quick and dirty binding of regular DOM ready present elements.
  • .bind() : which was just a more flexible version of bind.
  • .live() : for elements that were on the page and potentially would be added to the page later in the future.
  • and eventually .on() which was the one ring to rule them all. On was a unified version of all of the above.

Each method had their own nuances, pro's and cons. As things have progressed though, several of these have been deprecated and jQuery core team has advised the use of on.

The ABC's of event binding

In case you're unfamiliar with the in's and out's of event binding let's have a brief refresher. Event binding is when you take a element on the page and specify than when a certain action occurs, you then want the page to perform some other action. When the user clicks a button, I want this method to fire. When they hover over this button, I want it to change color. Event binding the process of tying a method to an an event on the page.

Event binding the process of tying a method to an an event on the page.

Let's take a simple example and see how it could be hypothetically bound:

In the above image of this post, when a user clicks on the save draft button, a hypothetical saveDraft method should be called. Let's see how we might go about wiring that up conventionally.

//$(id).on('event', handler)
$('#draft').on('click', saveDraft);

Above, I have annotated the signature. The #draft is the id of the button to be clicked on. click is the name of the event that is to be bound and lastly, saveDraft is the method name that will handle the event.

The method that will handle the event is known as an event handler.

This type of binding works for all events that are present on your page when the page is loaded. What happens though when the elements you want to bind aren't present when the page first loads? Such as with ajax events, or DOM manipulated actions.

Using delegated events to bind events to async elements.


Jquery's .on documentation