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
$(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