So, this might be a very simple question but I'll ask anyway. And this obviously is just to clarify in my mind how these two statements work.
Scenario I am pulling via an Ajax call some JSON that I then interpolate into html which has some selectors. Like this:
$.each(r, function(k,v){
str+='location: <div class=\'loc-to-select\' data-location-id=\'' + v.id + '\'>';
str+= v.name + '</div>';
});
$('#event-search-locations').html(str);
basically writing out:
<div class='loc-to-select' data-location-id='2'>Joe's</div>
I have these two pieces of jQuery:
// doesn't work
$('.loc-to-select').on('click',function(){
alert('here you go');
});
// does work
$(document).on('click','.loc-to-select', function(){
alert('here you go');
});
All of this clearly takes place after jQuery's $(document).ready has finished firing. It is my understanding that this is the main functionality that jQuery provides. I am familiar with the concept of event bubbling. I have also read the doc's here http://api.jquery.com/on/ where it discusses delegated events. I am not understaning internally how jQuery is doing this via descendent elements. Some of this discusses how it handles from a user space pov: Direct vs. Delegated - jQuery .on()
Also, it seems that the descendent element technique is preferred for performance reasons. Does the descendent element model basically say, if we get something new added to the DOM, check to see if it complies to the 'delegated element' model whereas direct events bypass this?
On a more simple level, does the jQuery 'runtime' essentially monitor the DOM for changes and then checks or does it check earlier in for example the html function (essentially parsing though html for items it knows about)?
Finally, why don't they just make the second syntax (the delegated syntax) the default? It would seem to provide greater specificity and better performance (as mentioned in the docs)
thx