简体   繁体   English

调用jquery .on(document.body)而不是特定元素是否有缺点

[英]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. 我正在将项目中使用的jQuery版本升级到最新版本。 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. .live函数在很多地方用于更改动态创建的显示并且运行良好,但.live功能在jQuery的更高版本中被删除,因此需要重新组装。

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. 即使不会对动态创建的对象执行click方法。

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. 考虑到它是一个内部网站,少量用户,并且所有元素都提供了id,你认为这个想法有什么不足吗?

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. 事件委托是一种推荐的模式,因为它有助于避免在事件处理程序附加到稍后从DOM中删除的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. 在大多数情况下,选择器强制JS通过DOM树,识别所有匹配,并将事件处理函数的新实例附加到每个匹配元素,它也更快。

While neither may be the case in a very specific ID example, there is no drawback to using it as a general approach. 虽然在非常具体的ID示例中都不是这种情况,但将其用作一般方法没有任何缺点。 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. 这正是.live()被弃用的原因,因为当你以这种方式绑定大量事件时,这是非常低效的。 For delegated event handling it is much more efficient to bind them to the closest parent that is not dynamic. 对于委派事件处理,将它们绑定到非动态的最近父节点会更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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