UI Developer at Bazaarvoice

jQuery .live() Gotchya

I was recently trying to fix a bug somebody introduced in our app, and after a bunch of digging I found the misunderstanding of $.fn.live.

tldr: cacheing a selector, then attaching a $.fn.live event listener, then attempting to use that cached selector (accessed via closure) can break.

// $.fn.live misuse
(function() {
// cache all elements that match this selector *as they exist on the page right now*
// let's say this is empty at this point in time
var $posts = $(".posts");
// set up a click listener. this is totally valid with $.fn.live,
// any new ".posts" that get added to the DOM will automatically respond to this
$posts.live('click', function() {
//update all the HTML of all the ".posts", this selector is still *EMPTY*
$posts.html("this doesn't work the way you might expect");
});
})();

The cached selector is not live, but attaching the event handler via $.fn.live works.

For this to work as expected, you’d have to do a re-selection within the event handler, instead of trying to use a cached selector.