Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Function Based on a String Which Contains the Function Name

var foo1,foo2;

switch (fn)
{
    case "fade"  : foo1 = "fadeOut"; foo2 = "fadeIn"; break;                
    case "slide" : foo1 = "slideUp"; foo2 = "slideDown"; break;
}

eval("$('.cls1')." + foo1 + "();");
currentSlideIndex = currentSlideIndex + n;
eval("$('.cls1')." + foo2 + "();");

Any better way to achieve this without using eval ? Im not a very big fan of using eval unless absolutely necessary.

like image 861
Phonethics Avatar asked May 04 '10 06:05

Phonethics


2 Answers

As the function names stored in foo1 and foo2 are properties of the object returned by $('.cls1'), the following should work:

$('.cls1')[foo1]();

Same with foo2.

like image 114
Tom Bartel Avatar answered Oct 05 '22 20:10

Tom Bartel


$('.cls1')[foo1]();
currentSlideIndex = currentSlideIndex + n;
$('.cls1')[foo2]();
like image 31
Amarghosh Avatar answered Oct 05 '22 20:10

Amarghosh