Blog

Coast Creative provides Adobe Business Catalyst e-commerce web development services and SEO for website
designers and online business owners.

Get Yourself in a Bind with jQuery .on()

Tuesday, April 10, 2012

I know, I know, I could have taken the low road with the title...

When I started developing for the Business Catalyst platform I was unsure how to deal with the loss of jQuery binding that occurred whenever the server updated a page behind the scenes. 

The shopping cart was especially tricky. Using jQuery to rename server-generated labels and perform other housekeeping duties was great, until the user selected an input that caused the server to update the page. Bye, bye event handler!

After a lot of head scratching I came up with a solution: jQuery's .delegate() method. This method allows you to, and I quote "Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements." Cool! Especially the "now or in the future" part!

This method was a life saver when modding BC pages with Ajax interactions. But hey, life moves on.

As of jQuery 1.7 the delegate() method has been superseded by the jQuery .on() method. This new 'super-method' replaces .bind(), .delegate() and .live().

All that's required to keep your event handlers from breaking on a server-generated element is to attach the handler to a DOM object that doesn't get refreshed using .on(). An extreme example of this would be attaching the event handler to the HTML body element. If that were the end of it it wouldn't work out very well because your event would be attached to, ummm, the body. Not very useful, that's for sure.

The magic happens when you supply a selector to the .on() method. The selector filters out any other potential event triggers so the event is essentially bound only to the element supplied to the method. 

Example:

jQuery('body').on('change','#ShippingOptions', function() {
  alert("I'm still bound!");
}

This code snippet attaches the change event to the body element but it will only be triggered by the select input with an ID ofShippingOptions, even though Business Catalyst will destroy and replace the code on the page when a user makes a new selection.

Comments