Event Delegation With JQuery

A Popup Calendar Icon




A Calendar Popup Icon



A Calendar Popup Icon


<form>  <p>    <label for='start_date'>Start Date</label>    <input id='start_date' type='date'>    <i class='calendar'></i>  </p>  <p>    <label for='end_date'>End Date</label>    <input id='end_date' type='date'>    <i class='calendar'></i>  </p></form>

The Old Way




$(function(){
  $('.calendar').click(function(){
    showCalendarPopup();
  });
});

The Old Way


What's This For?
$(function(){
  $('.calendar').click(function(){
    showCalendarPopup();
  });
});

The Old Way


What issues could this have?

$(function(){
  $('.calendar').click(function(){
    showCalendarPopup();
  });
});

The Old Way



  • Need to wait until DOM is ready to bind events
  • Selectors tie presentation and behavior together
  • Memory leaks if DOM elements removed incorrectly
  • If we add another .calendar, it won't have the binding

live() To The Rescue!




$(function(){
  $('.calendar').live('click', function(){
    showCalendarPopup();
  });
});

Well, Maybe Not



  • Need to wait until DOM is ready to bind events
  • Selectors tie presentation and behavior together
  • Memory leaks if DOM elements removed incorrectly
  • If we don't add a new .calendar, it won't have the binding

A New Way



$(document).on('click', '[data-calendar]', function(){  showCalendarPopup();});

A New Way



$(document).on('click', '[data-calendar]', function(){  showCalendarPopup();});

A New Way

Event Bubbling

<form>  <p>    <label for='start_date'>Start Date</label>    <input id='start_date' type='date'>    <i class='calendar' data-calendar></i>  </p>  <p>    <label for='end_date'>End Date</label>    <input id='end_date' type='date'>    <i class='calendar' data-calendar></i>  </p></form>

A New Way



$(document).on('click', '[data-calendar]', function(){  showCalendarPopup();});

A New Way



  • Bind as soon as javascript executes
  • Can use more complex selectors and segregate presentation and behavior
  • No memory leaks from dangling DOM elements
  • Every element that matches '[data-calendar]' is correctly bound, regardless of when it shows up on the page

A New Way

One Gotcha




Delegation will always find the outermost element
in a nested situation

Questions?

Event delegation with jquery

By blatyo

Event delegation with jquery

  • 767