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

5 Answers 5

4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

4

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

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

Comments

1

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.

Comments

1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.