[英]What's more efficient when delegating methods?
I have a site full of AJAX so I need to delegate methods to document clicks, assuming I have jQuery library too. 我有一个充满AJAX的网站,因此我需要委托方法来记录点击次数,假设我也有jQuery库。
I just want to know what's more efficient between these two codes: 我只想知道这两个代码之间更有效的方法:
$(document).on('click', '.delegate1', function(){
doSomethingForDelegate1();
}).on('click', '.delegate2', function(){
doSomethingForDelegate2();
});
Or: 要么:
$(document).on('click', function(event){
var element = $(event.target);
if(element.hasClass('delegate1')){
doSomethingForDelegate1();
} else if(element.hasClass('delegate2')){
doSomethingForDelegate2();
}
})
I want to implement the code that will have less impact on client's execution time and therefore have a faster site. 我想实现对客户端的执行时间影响较小的代码,从而使站点更快。 I know that maybe the difference won't be much but it's always better to work faster ;) 我知道也许差异不会太大,但是更快地工作总是更好;)
If there's a method that's faster than these 2 methods it's welcome too. 如果有一种方法比这两种方法快,那么也欢迎。 Thanks. 谢谢。
If the difference isn't noticeable enough then I want to know what algorythm is cleaner, binding an event for each delegate or bind a single event and compare classes. 如果差异不够明显,那么我想知道哪种算法更干净,为每个委托绑定一个事件或绑定单个事件并比较类。
The 2nd method can be efficient when there are many elements that are being added to the DOM at a later time. 当稍后有许多元素添加到DOM时,第二种方法可能会很有效。 SO attaching a single event to the document and delegating can really speed up the application . 因此,将单个事件附加到文档并委派确实可以加快应用程序的速度。
But if the number of elements created and needed to be attached are not huge, both should perform at the same rate.. 但是,如果创建并需要附加的元素数量不多,则两者应以相同的速率运行。
I would go with the 1st approach as it is lot more cleaner. 我会采用第一种方法,因为它更清洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.