1

How can I have a parameter to one JS function be Function Name with parameters to call another function?

something like:

onClick="Clicked(this, 'SomeFunction('test')'"

Regards

5 Answers 5

11
onClick = "Clicked(this, function () {SomeFunction('test')});"


function Clicked (obj, functionToFire)
{
   functionToFire();
}
Sign up to request clarification or add additional context in comments.

9 Comments

ok inside of the Clicked function how do I call the SomeFunction using the var passed to Clicked function?
@OutOFTouch Is that what you are asking?
Assuming SomeFunction already exists, this will call it right and not create an anonymous function? I am getting an exception ; is missing, do I need to add a semicolon just before the closing }?
@OutOFTouch Can you post your code around that? You don't "need" to add a semi colon, but it is good practice.
I am generating this script from server code, I accidentally included an extra open paren, removed that and it doesn't throw any errors. I was just trying to get the syntax correct now I will try calling the method from the other method like you showed above.
|
2
<span onclick="Clicked(this, 'SomeFunc', ['test', 123])">AAAA</span>

...

function Clicked(thisObject, funcName, params)
{
 // find an object with name funcName in default (window) scope
 var func = window[funcName];

 // test that the object exist and that it's a function
 if (func && typeof func == "function")
 {
  // call the function with passed params
  // passing 'thisObject' enables to use 'this' keyword within the called function
  func.apply(thisObject, params);

  // as an alternative you may call it without 'this' object
  func.apply(null, params);
 }
}

function SomeFunc(text, num)
{
    alert("text: " + text + ", number: " + num);
}

Comments

1
<script>
function doSomeWork(arg1, arg2)
{
    arg2();
}
function displayThis(msg)
{
    alert(msg);
}
doSomeWork("11",function(){ displayThis("123");});
</script>

1 Comment

I think you meant to pass arg1 to arg2 like: arg2(arg1);
-1

What you have would work, although, you'd need to use the javascript eval function to evaluate the value once in the function:

function Clicked(obj, functionText)
{
   // do something with object....
   eval(functionText);
}

Otherwise, if there's no parameter, you can always pass the function itself:

onClick="Clicked(this, SomeFunction)"

and implement like this:

function Clicked(obj, func)
{
    // do something with object...
    func();
}

1 Comment

Note that it would be very amateurish to use eval for something like this. eval has it's use(s?), this isn't one of them.
-1

This couldn't be simpler:

onClick = "function() { someFunction('test') }"

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.