简体   繁体   中英

Is there a downside to calling jquery .on(document.body) rather than the specific element

I am upgrading the version of jQuery used in a project to the latest and greatest. The .live function was used in numerous places to change dynamically created display and worked great, but the .live functionality was removed in later versions of jQuery thus necessitating a retool.

As a way of standardizing the coding I am considering calling the function as:

$(document.body).on('click', '#clickableElement', function(){})

rather than

$("#clickableElement').on('click', function(){})

even if the click method will not be performed on a dynamically created object.

Do you see any downfalls to this idea considering it is an internal website, small number of users, and all elements are provided id's.

Event delegation is a recommended pattern because it helps avoid memory leaks that are possible when event handlers are attached to DOM elements that are later removed from the DOM.

It it also faster in most cases where selectors force JS to travel through the DOM tree, identify all matches, and attach a new instance of an event handler function to each matching element.

While neither may be the case in a very specific ID example, there is no drawback to using it as a general approach. The only real downside to delegation at the root of the document is the risk of something canceling the event before it gets to the body which prevents it from bubbling to your handler.

Event delegation does not always make your code faster. In some cases, it's is advantageous and in some cases not.

You should use event delegation when you actually need event delegation and when you benefit from it. Otherwise, you should bind event handlers directly to the objects where the event happens as this will generally be more efficient.

Also, you should not bind all delegated events at the document level. This is exactly why .live() was deprecated because this is very inefficient when you have lots of events bound this way. For delegated event handling it is much more efficient to bind them to the closest parent that is not dynamic.

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