简体   繁体   中英

Jquery On event. Delegate and speed issue

I'm using in my code few events like:

$( "body" ).on( "click", '.editButton', clickFunction);

And it creates events for every element inside Body that has class .editButton. I add this event to the Body element as i don't know where can I have this buttons in the code, sometimes i'm doing many ajax requests to different parts of the site and I want them all to fire clickFunction. What impact has this method to the general page speed? What if I have 5-6 such a delegate events. I'm not sure how it works. If I add some new html elements via Ajax call to the page does the script search every Body element for .editButton element and creates click event for it? And when I have few such events will it bo done like that few times? How fast is it? Is it something we must be concerned about?

If I add some new html elements via Ajax call to the page does the script search every Body element for .editButton element and creates click event for it?

Well, this is not quite how Event Delegation in JavaScript works. You attach the event handler only once to the parent node. In your case the body tag.

Now when any event, anywhere, on any node happens, the event propagates up the DOM tree. (Event Bubbling). Once it hits an event handler, the target of the handler is checked and the callback function is executed with it.

In your case, whenever the edit button is clicked, (or whatever button is clicked), the event travels up, to your body where you have a click handler. It sees that the target is the .editButton and JS knows this is the target of your handler.

As you can see, the only way your performance would degrade is when you have a dom tree that is too deep. That is why its a good pratice to add the event handler to a common parent and always to the body or document that some use.

So adding more such buttons wont cause any increase in performance issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM