views:

87

answers:

5
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.

+4  A: 
$('.cls1')[foo1]();
currentSlideIndex = currentSlideIndex + n;
$('.cls1')[foo2]();
Amarghosh
+4  A: 

You don't need to use eval, you can simply use the bracket notation property accessor:

$('.cls1')[foo1]();
CMS
+3  A: 

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.

Tom Bartel
+1  A: 

You can use the syntax:

$('selector')[foo1]();

However another approach to dynamically call the method is to create a new method, that deligates

(function() {
  $.fn.someFunc = function(what)
  {
    switch(what) {
      case 'fadeOut':
        $(this).fadeOut();
        break;
        // etc
      default:
        // handle an unknown value
    }
  }
})(jQuery);

$('.cls1').someFunc('fadeOut');

This will allow you to quickly control what happens instead of passing anything as foo1.

Ben Rowe
+1  A: 

You can use this strategy to fit your needs:

function doFade() {
  alert('fade');
}

function doFadeIn() {
  alert('fadeIn');
}

var fns = {
  'fade': doFade
  , 'fadeIn', doFadeIn 
};

function callSomething(what) {
  fns[what]();
}

// callSomething('fadeIn'); => alerts 'fadeIn'
npup