Is there someone who might be able to explain why using a function such as
$('#potato').delegate('.frenchFry', 'click', function(e){
// do something...
});
is better than
$('#potato').bind('click', function(e){
if($(e.target).hasClass('frenchFry'){
// do something...
}
});
assuming a large number of delegations on a very dynamic and constantly changing #potato? is there a speed advantage to using delegate (not from any tests i could come up with)?
Because e.target
will refer to the most deeply nested element clicked, which may not have the class you're looking for.
<div class="frenchFry>
<span>some nested text</span>
</div>
$(e.target).hasClass('frenchFry') // click on the <span> will return "false"
If you're certain that the actual e.target
will always be the element you intend, then this won't be an issue.
Having a selector based .delegate()
that tests more than just the e.target
itself simply makes it a little more dynamic.
EDIT: By the way, you could sort of replicate .delegate()
something like this:
var node = e.target;
while( node && !$(node).is('.frenchFry') ) {
node = node.parentNode;
if( node === this || node === document.body ) {
node = null;
break;
}
}
if( node ) {
// do something
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With