Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple on() or switch() within one on()

I have a menu on my page and am currently writing the script that sets all the click events for the menu buttons. Each button will call its own method so it must be set explicitly.

My question, quite simply, is which of the following two methods is better to use in this situation:

$(document).on('click','#menu .button', function(){
    switch($(this).attr('id')){
        case 'foo_button':
            // Set the event for the foo button
        break;
        case 'bar_button':
            // Set the event for the bar button
        break;
        // And the rest of the buttons
    }
});

Or:

$(document).on('click','#foo_button',function(){
    // Set the event for the foo button
});
$(document).on('click','#bar_button',function(){
    // Set the event for the bar button
});
// And the rest of the buttons

I would have thought option 1 would be better as it only sets one event... However, this event will be called on every click of the menu buttons, so it is hard to know which would be more efficient.

like image 716
Ben Carey Avatar asked Nov 02 '22 20:11

Ben Carey


1 Answers

If the handler function is truly different for each different button ID, then each should be registered using its own call to on().

It's probably not going to make a noticeable difference in the performance of your code, but it will make things much easier to read for other developers (or even yourself for maintenance) in the future.

like image 109
Justin Niessner Avatar answered Nov 12 '22 16:11

Justin Niessner