Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortening javascript switch

I have a piece of code like this:

switch(v[0]){
    case 1:
        $(o).test({default:true}).on("click", function(e){
            stopf(e);
            func1(v[1]);}           
        });
        break;
    case 2:
        $(o).test({default:true}).on("click",function(e){
            stopf(e);
            func2(v[1]);}           
        });
        break;
    case 3:
        $(o).test({default:true}).on("click",function(e){
            stopf(e);
            func3();}       
        });
        break;
    case 4:
        $(o).test({default:true}).on("click",function(e){
            stopf(e);
            func4();}       
        });
        break;
    case 5:
        $(o).test({default:true}).on("click",function(e){
            stopf(e);
            func5(v[1],v[2]);}          
        });
        break;

    // AND ON AND ON....
}

As you can see the only difference is the funcX() part at the end of each line. Is there any way to shorten this code? Maybe something like this (tried it, doesn't work):

switch(v[0]){
    case 1: myfunc=func1(v[1]);break;
    case 2: myfunc=func2(v[1]);break;
    case 3: myfunc=func3();break;
    case 4: myfunc=func4();break;
    case 5: myfunc=func5(v[1],v[2]);break;
}
$(o).test({default:true}).on("click",function(e){
    stopf(e);
    myfunc);
}
like image 356
Michel Avatar asked Feb 20 '26 11:02

Michel


1 Answers

Put the functions in an object:

var funcs = {
    1: function() { func1(v[1]); },
    2: function() { func2(v[1]); },
    3: func3,
    4: func4,
    5: function() { funct5(v[1], v[2]); }
};

Then use this when binding the click handler:

$(o).test({default: true}).on("click", function(e) {
    stopf(e);
    funcs[v[0]]();
});

Notice that you have to wrap all the calls with function() { ... }. Otherwise, you'll call the function when you're assigning the variable, not when the event is triggered.

like image 87
Barmar Avatar answered Feb 22 '26 02:02

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!