JavaScript – Detour from Response Dialogs

In my previous article, I was saying that you can even use a response dialog to modify variables, or control flow, at runtime. If you’ve got a function that you need to wring out thoroughly, set it up so that you can input values dynamically via a response dialog.

You can even enter code into the response dialog at runtime. Here’s an example showing how:



x = 5;y = 8;str = app.response('Enter some code.');func = new

Function(str);app.alert( func() );

If you run this code and (when the dialog comes up) enter ‘return x * y’, an alert will

appear with the value ’40’ displayed. If you had entered ‘return x/y’, the alert would come

up with ‘0.625’ showing.

What’s happening is that the response dialog (the line of code beginning with str =,

above) is giving you a chance to type some JavaScript in ordinary ASCII. Whatever you type

is captured into a string, str. The trick is to get this string to execute now, while

your Form is up and running. It turns out we can do that, if we take the string stored in

str and submit it as the argument to the Function constructor.

Let’s back up and talk about declaring functions in JavaScript. You’re probably familiar

with the following way of declaring a function:


function myFunc( x, y) { (some code here) }

The keyword ‘new’

This is fine for setting up a function whose content is known prior to runtime. Most of

the functions you’ll write will be set up this way. But there is another way to declare a

function: namely, using the Function constructor. This implies using the new keyword.

The constructor takes, as an argument, a string containing whatever code statements you want

to put in the function. The constructor returns a Function object, as in:

theFunction = new Function(str)

Here, theFunction is our new Function object. To call it, we just use the

parentheses operator in the normal way:

theFunction();

If the function returns a value, then just capture the value in a variable as you

normally would.

Note carefully what we’ve been able to do. We’ve found a way to turn a string into

a function (using the Function constructor). Since strings can be captured at runtime

(via dialogs, form fields, and so on), this means we can actually create new

functions at runtime, from strings entered at runtime. We can actually insert new

code into already-running code, using a response dialog… and run the new code!

You May Also Like

About the Author: Kas Thomas

Leave a Reply