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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With