Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To use delegate() or not

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)?

like image 754
borbulon Avatar asked Oct 10 '22 06:10

borbulon


1 Answers

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
}
like image 152
user113716 Avatar answered Oct 20 '22 05:10

user113716