Search code examples
javascriptintrospectiondynamic-function

How to evaluate a full function string (including params) in javascript


I have a select (dropdown list) with options which correspond to actions. Each action corresponds to a generic javascript function that should be called on the changed event for the select. So it looks like this:

<select id="id-select-action" class="select-action right" value="Actions">
            <option class="select-title">Actions</option>
            <optgroup label="General Actions">
                <option value="load_new_page('/url/to/new/page')">create a foo</option>
                <option value="load_cbox('/url/to/cbox/contents')">manage tags</option>
            </optgroup>
</select>

My server code is dynamically generating each option's value strings (which are calls to javascript functions, depending on what the action does and how it is displayed) and the server also dynamically generates the parameters (the urls to the views).

I have a jquery listener on the change event for the select, which I want to call the javascript function in the value string in the option.

$("#id-select-action").change(function() {
    function_call = $("#id-select-action option:selected").val();
    //How do I execute the function_call?

});

It seems everyone hates eval() . . . but is this a proper case for it, or should i be doing something else? I looked at this How to turn a String into a javascript function call? . . . but in that one, you only have the name to deal with, not the full function call string, including the parameters.

The reason I'm doing it this way is because I'm creating a general framework for certain types of views of our application, and the actions may be different (and have different url's and/or call a different javascript function) for each page.

Thanks!


Solution

  • I think eval will help.. in the condition.

    http://www.w3schools.com/jsref/jsref_eval.asp

    But please be careful about using eval and check conditions if its fits in your case.