Is it better to have multiple handlers for button click events, or is it suitable to combine click handlers with a switch statement? This works in my code, but I was wondering, is there a cooler, more JQuery-istic way to do it?
<html>
<button id="button1">Button 1</button>
<button id="button2">Button 2</button>
<button id="button3">Button 3</button>
</html>
Which is better, this?
$('button').click(function(){
switch(this.id){
case "button1":
alert("Do what button 1 says");
break;
case "button2":
alert("Do what button 2 says");
break;
case "button3":
alert("Do what button 3 says");
break;
}
});
Or this,
$('#button1').click(function(){
alert("Do what button 1 says")
});
$('#button2').click(function(){
alert("Do what button 3 says")
});
$('#button3').click(function(){
alert("Do what button 3 says")
});
…Or is there no difference?
It all depends on the event handler. If there is shared code between the handlers and only a small part is specific, it might be fine to distinguish between the buttons inside the handler.
If each button handler is totally different though, why put three unrelated functions into one?
You can also create a map of functions:
and simply call a function with
handlers[this.id]().In the end, you assign an even handler to each element one way or the other, so it’s more a matter of how you want to structure your code (which is personal preference more or less).