Avg. Rating 2.8

Problem

You need to execute JavaScript in the browser to accomplish some task. Your code, however, is becoming a mess of strings with escaped quotes. Or worse, you've added an external dependency by adding the needed function to the containing page.

Solution

Leverage the XML data type to wrap needed JavaScript inside the SWF. Our JavaScript will be easy to read (syntax highlighting, no extra charge), and will be located next to the code that uses it.

Detailed explanation

Here are two ways to attach JavaScript to the containing HTML page at run time. In both examples, the XML is nothing more than a snippet of JavaScript; we just attach and call them differently.

Anonymous Functions

This example illustrates how to use an anonymous function, which you just call each time you need that snippet to run.

private static const SHOW_ALERT:XML =
    <script type="text/javascript">
      <![CDATA[
          new function(text) {
              alert(text);
          }
      ]]>
    </script>;

Which is called like so:

ExternalInterface.call(SHOW_ALERT, "Hello, world!);

JavaScript Object

This example shows how you can group all your JavaScript together, and just include it once, calling the attached methods as needed.

Here is the code to attach the object:

ExternalInterface.call("eval", TOOLKIT);

Here is the XML constant:

private static const TOOLKIT:XML =
  <script type="text/javascript">
    <![CDATA[
      Toolkit = {
        showAlert: function(text) {
          alert(text);
        }
      }
    ]]>
  </script>

Which is called like so:

ExternalInterface.call("Toolkit.showAlert", "Goodbye, cruel world.");

 

AlertJavaScript.zip
[A Flex Project Archive (Flex Builder 3) illustrating the concept.]
Report abuse

Related recipes