jQuery 1.4.2 added the ability to delegate events. jQuery 1.7 blanketed delegation and "on-the-fly" event binding under one method – on().
So, what does this all mean, and why is it useful? I started dabbling with delegation, sprinkling it into my code where it made sense, but it gradually occurred to me that using delegation to bind all events made sense for two reasons:
- "Future proof" against any changes to the DOM
- Code is far easier to read
- Code is far easier to debug
Essentially, delegation allows a parent object which is more "stable" (always exists) to handle binding events to elements as they are created.
As an example, let's say you have a function which creates a new element, and assigns a click event to it:
<div id="wrapper">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
<script type="text/javascript">
$('.item').click(function() { /* do something */ });
function createDiv() {
$('#wrapper').append('<div class="item" />);
$('.item').unbind().click(function() { /* do something */ });
}
</script>
As you can see in the code above, we not only had to create event binding code in two different places, but we had to unbind all the existing click events before binding new ones. With event delegation, this whole process becomes a great deal simpler:
<script type="text/javascript">
$('#wrapper').on('click', '.item', function() { /* do something */ });
function createDiv() {
$('#wrapper').append('<div class="item" />);
}
</script>
With the on method, we are telling #wrapper not only to assign click events to any existing children .item elements, but to assign the click event to any .item elements create in the future.