user2320724
user2320724

Reputation: 676

How to execute string containing function name AND parameters?

In javascript, I have a string like this:

"doSomething('param1','param2')"

And I want to execute it. I am aware that I could normally use

window['doSomething']('param1', 'param2');

But that only works if my function name is separate from the arguments. In my case they are already combined. I think I can use eval() but the consensus seems to be that it should be avoided. Is there another way?

EDIT: To answer the request for more info: I am using this string like this:

<a id="YesButton" onclick="closeModalView_Yes("doSomething('param1','param2')")">

Where closeModalView_Yes will close the modal yes/no window and then execute the given function, although at times I may pass it doSomethingElse(param1) which only takes one parameter.

Upvotes: 0

Views: 113

Answers (2)

Bergi
Bergi

Reputation: 664395

<a id="YesButton" onclick="closeModalView_Yes("doSomething('param1','param2')")">

You really shouldn't pass that as a string, but as a function:

closeModalView_Yes(function(){ doSomething('param1','param2'); });

together with

function closeModalView_Yes(callback) {
    // do whatever needs to be done to close the window
    // and after that
    callback();
}

Btw, with your current approach the HTML is not even valid, it would need to be

<a id="YesButton" onclick="closeModalView_Yes(&quot;doSomething('param1','param2')&quot;)">
<!--                                          ^^^^^^                              ^^^^^^ -->

You could've avoided that by registering the event via javascript instead of inline attributes.

Upvotes: 1

oleq
oleq

Reputation: 15895

Use eval, just like:

eval( "console.log( 'hey', 'here I am' )" );

However eval is pretty dangerous and it's not recommended.

If you can (still we don't have much info about your case), render your JavaScript between <script> tags in your template, making it a "regular code", much easier to debug.

Also a good practice is to pass data (i.e. with JSON) rather than code. Try rethinking your logic or provide additional information.

Upvotes: 1

Related Questions