简体   繁体   中英

Javascript multiple functions versus larger functions

if I have 10 buttons, am I better to have an event listener that points to each button and calls a different function:

hdlButton1.addEventListener("click", fButton1Clicked);
hdlButton2.addEventListener("click", fButton2Clicked);
etc.

function fButton1Clicked(event) {
    //code to execute upon button 1 click
}
function fButton2Clicked(event) {
    //code to execute upon button 1 click
}

Or have all the clicks point to a single function:

 document.addEventListener("click", fButtonClick);

 function fButtonClick(event) {
     switch (event.target.id) {
         case "btn1":
              //code to handle button 1 click
              break;
          case "btn2":
              //code to handle button 2 click
              break;
        }
}

What are the implications for performance in having multiple functions to handle the various events versus having a single function that differentiates between the events and handles appropriately?

(Thanks)

The performance impact is quite negligible on modern computers unless you have an unreasonably huge number of buttons and functions. Better to worry about code readability and maintainability first - only think about performance issues once you have evidence that it's a non-negligible problem.

The time difference is negligible in both the cases, however I think using different functions would have better performance as there is one less branch statement.

As far as the code readability goes, I use single function when the buttons are doing similar job with different parameters and different functions when the jobs are different.

From a performance point of view, it is always recommended to have as few listeners as possible , especially if you dynamically add/remove buttons or elements which have listeners attached.

What you did in the second case is called event delegation , and it's really useful when you have dynamically created elements and you want the listener to be triggered on nodes created after the listener was added.

Performance difference will not be noticeable, unless you need it for a high-performance app (eg. a game), so you should usually go with whatever is more readable, or with delegation if you have dynamically changing elements.

I have actually created a small library to easier implement event delegation for created elements: https://github.com/Cristy94/dynamic-listener

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