jQuery live()

I’ve been working with jQuery for a little while, but because I didn’t read the API from start to finish, I’ve managed to discover some little things along the way. In my Rails apps, I typically have links/button that invoke an Ajax call to the server to render a partial and add it into the DOM somewhere (such as adding an Address partial to a Contact form). Often, I would have some masked entry fields (using jQuery Masked Input) or date pickers or something else that needed to be adorned  with the appropriate JS. Typically I would write some Javascript at the end of the partial rendering that would call some functions to go and reapply the right bindings, such as $(‘.time_field’).mask(’99:99′) for all of the  inputs of class .time_field or adding click functions for links.

The problem I typically ran in to was that I was continually binding the same event handlers on top of already existing handlers every time the Ajax was invoked. In those cases, I had to unbind the event handlers before binding the new event handler which seemed like a lot of extra work for no good reason: $(‘.some_class’).unbind(‘click’).click( function… or $(‘.time_field’)unmask().mask(’99:99′).

That lead me to my discovery of the  live() handler. live() allows you to bind events for all objects matching a selector at the time of execution AND for any new items added to the DOM. This lead to further simplification of my code. No longer did I need to tack on a little JS function when returning my rendered partial to adorn the fields needing extra behaviours when live() would take care of that for me. I really wish I knew about that before.

Advertisements
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: