3

I just need the logic and understanding on how I can do this.

The problem:

I have several functions that are very similar but I want to create/call the dynamically

Example:

$(document).ready(function() {         
    function foo() {
        $("#foo_elem").toggle(true).attr('required', true);
        alert('This is foo');
    }

    function bar() {
        $("#bar_elem").toggle(true).attr('required', true);
        alert('This is bar');
    }
});

How can I pass in foo/bar to create the function? Pseudo code

$(document).ready(function() { 
    // would pass foo/bar to this?        
    $($x)(function() {
        $("#"+$(this)+"_elem").toggle(true).attr('required', true);
        alert('This is '+$(this));
    });
});
1
  • 1
    Maybe your example doesn't cover the extend of your problem, but can't you just use one method with an argument? Commented Apr 7, 2011 at 15:19

2 Answers 2

10

You want to dynamically call foo or bar?

function callMethod(method)
{
     method();
}

callMethod(foo); // foo is the symbol for your method
callMethod(bar); // etc

At a high level. In your instance, though, you're asking to use that symbol as just a variable in your selector:

function callMethod(elementPrefix)
{
    $('#' + elementPrefix+ '_elem').toggle(true).attr('required', true);
    alert('This is ' + elementPrefix);
}

If you want to use it both as a string value, and the method name, you can eval the symbol to get the method:

var methodName = 'foo';
var text = 'This is ' + methodName; // This is foo
var method = eval('(' + methodName + ')');
method(); // calls foo()
Sign up to request clarification or add additional context in comments.

Comments

4

I'm not sure if I understood your question fully, but do you want to dynamically create a function based on some arguments? If so, you could do something like this:

function make_func(x) {
  return function() {
    $("#"+x+"_elem").toggle(true).attr('required', true);
    alert('This is '+x);
  };
}

Then make_func('foo') would return a function which is equivalent to the function foo in your original example.

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.