Sonntag, 2. Februar 2014

Delegate Javascript! ...if you can.

Unobtrusive Javascript is the modern way to code Javascript, as I already stated in "Be always unobtrusive!". On this basis you can go even one step further: event delegation. How event delegation works in detail is well explained by the W3C. Please read about the event capture and event bubbling carefully.
Here I want to give a revealing example. Therefore I will extend the "Unobtrusive Javascript" example inserting some additional list elements.
I use jQuery to help me out writing the example, but event delegation is not library specific.
The index.html was extended with an input element:
  • Ruby
  • Python
  • Javascript
And the application.js:
$(document).ready(function(){
  $("#languages li").click(function(event){
    $(this).toggleClass("selected");
  });
});
  • Ruby
  • Python
  • Javascript

Please try it and type in your favourite language and hit the enter key. It will be added (as a simply Ajax response also could do). But also note that your new added language won't be marked green, clicking on it.
It's because the Javascript was observed directly to the list element.
Delegating the event and its functionality to the container 'ul' will solve the issue. The changed application.js:
$(document).ready(function(){
  $("#languages").delegate("li", "click", function(event){
    $(this).toggleClass("selected");
  });
});
Please note the jQuery function 'delegate'. It does the job and delegates the Javascript click event to the 'ul' container element.
Try it, add a new language and click on it:
  • Ruby
  • Python
  • Javascript

Event delegation saves you massive direct observes.

Supported by jQuery 1.10.2

Keine Kommentare:

Kommentar veröffentlichen