I am interested in knowing when bind function should be used and when delegate function should be used in jquery. Do they not perform the same functionalites? What is the difference?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You use
bind(or better yet,on, asbindis deprecated; noted by @Yoshi) when you have a few, existing elements you want to bind event listeners to. You usedelegatewhen the elements you want to handle do not exist yet (e.g. they are dynamically generated and you don’t want to bind handlers to each new element you create, but they have a common parent you can put the delegate on), or when you’re handling events on a lot of elements with a common parent (which is more efficient with a delegate on the parent than with individual handlers on each element).DOM events bubble up the DOM hierarchy, so when you click on an element
onclickhandlers for that element are triggered, then handlers on its parent, then its parent, and so on (unless a handler callsstopPropagationon the event, which cancels the further bubbling up. When you usebind/on, you attach your handler to the specific element you want to handle, and it is triggered directly by the target you’ve set it up on; when you usedelegate, a jQuery internal handler is attached to the element you specify, and it catches the event on its way up the bubble chain; jQuery then checks if the actual target (which is a child of the element the handler is attached to) matches the selector you’ve specified with the delegation, and if it is it is invoked (it is called as if your actual handler was attached to the target element and not the parent element; noted by @shannon).