简体   繁体   English

委托方法时,什么更有效?

[英]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.

相关问题 还有什么比JavaScript具有更高内存效率的IIFE? - What's more memory efficient IIFE in javascript? 这两种方法哪个更有效? - Which of these 2 methods is more efficient? Javascript:什么更有效,IF块或TRY / CATCH? - Javascript: What's more efficient, IF block or TRY/CATCH? 间隔发出请求的更优雅,更有效的方法是什么? - What's the more elegant and efficient way to make a request at intervals? 什么更有效? 检查==或只是改变变量? - what's more efficient? checking == or just mutating the variable? setTimeout与事件绑定/解除绑定; 有什么更有效的? - setTimeout vs. Event binding/unbinding; what's more efficient? 在这些$ .each循环中,更快/更有效/更好的是什么? - What is faster/more efficient/better when it comes to these $.each loops? “固定” for循环-更有效的方法是什么? - 'Fixed' for loop - what is more efficient? 在两个(或更多)数组中找到匹配的单元序列的最有效方法是什么? - What's the most efficient way to find matching sequences of cells in two (or more) arrays? 使用jQuery UI可调整大小的工具时,检查宽度的更有效方法是什么? - What is a more efficient way of checking for width when using the jQuery UI resizable tool?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM