— Tech+Life+Music

The understated beauty of jQuery’s new .on() and .off() functions

The latest version of jQuery (that is, 1.7.1, or 1.7.x) has been around for a good while already, and the new .on() and .off() functions still come to me as the shiniest new toys that came along with it. Not only are they shorter, more intuitive and better at what they do, but they also promote (generally) accepted jQuery good practice that has been around for quite a while.

What am I talking about?

If you’re any jQuery programmer worth your salt, then you know of, at the very least, .bind() and .live() when it comes to DOM event handling. The main difference being that the former is preferred for present elements, and the latter is “mandatory” for future element handling.

One or two rungs up the jQuery programmer ladder, and you’d know of .delegate() as well. If you actually use it with convicted priority over .live(), then you’re golden. An explanation of why would require a good grasp of how jQuery handles events behind the scenes, followed by a primer on why using .live() is bad.

It’s admittedly a pet peeve of mine. And I’d like to think that the reason why .live() persists so sturdily when .delegate() is most clearly a better choice (aside from the fact that the latter was introduced one major version step later in the jQuery lifetime), is that .live() is so much easier to type.

Isn’t it? I mean look at it.

// live
$('a').live('click', do_backflips);
 
// delegate
$(document).delegate('a', 'click', do_backflips);

Sheer convenience.

.on() and .off()

Which is a big reason why I -heart heart heart- the new .on() and .off() functions in jQuery 1.7.x. It streamlines all your event handling into just two functions, whether or not you’re taking into account present or future elements.

If you’re not familiar, the usage for .on() is like this:

// for present elements
$('a').on('click', do_backflips);
 
// for future elements
$('#container').on('click', 'a', do_backflips);

I’d suggest you also take a look at the official documentation for the on and off functions as well. Pretty spiffy.

What’s really nice is that both versions of .on() map to .bind() and .delegate() respectively, which has the added benefit of simplifying the question of what function to use on any given case, and cleaning up syntax. And, hey, it’s also easy and intuitive to use.

Additionally, .live() has also been deprecated as of jQuery 1.7.x. I quote:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

Frankly, one could argue that good practice is being forced down the programmers’ throats. But as it plays on clear improvements on jQuery’s event model, I don’t mind that one bit.

Feel free to start a discussion.
Submit comment