Frontal Scripting

From Frontal Wiki

Jump to: navigation, search

Frontal has another facet -- it's scripting language. It's a lightweight approach designed to provide interactivity to your Frontal site. And again, like JavaScript, it's embedded right into your Frontal document and evaluated (or "interpreted") only when someone visits that web page.

Some of the things you can do with Frontal's scripting language are:

  • Create content dynamically by writing to the Frontal document.
  • Add interactions to respond to visitor events (like clicking the mouse button) or to internal Frontal events (like loading an external resource).
  • Interact with the browser through Flash's ExternalInterface, both by making calls to and receiving calls from JavaScript.
  • Interface with web services like Google Maps and Twitter.
  • Validate form data.

Some things you can do with Frontal's scripting language are quite complex, but in general you don't have to be a programmer to use it. It's designed to be powerful enough to solve many problems, but still usable by those of us without a lot of programming knowledge. A common way to use it is by copying and pasting code snippets into your Frontal document, much like you would with JavaScript.

A big difference versus JavaScript is that Frontal doesn't implement the same Document Object Model (DOM). That is, JavaScript provides objects like 'window' and 'document' and various interfaces on the objects to interact with the document. Frontal also provides objects and interfaces to interact with the document, but they're different and depend more on the environment provided by Flash ActionScript 3.

Regardless of how much JavaScript or ActionScript you know, you'll pick up Frontal's scripting approach in no time.

Contents

How to Use It

There are two ways to run scripts in your Frontal document. The first is to use the 'script' tag.

<script><![CDATA[
    document.write ( "Hello World!" );
]]></script>

In this example the script is run when the Frontal renderer encounters the 'script' tag. The renderer will read the contents of the tag and interpret it as a script. In this case, the script is running a standard function called 'document.write' that writes a string directly to the Frontal document, where it'll be treated like typical Frontal markup code. (Frontal is more of a stickler about writing to the document than JavaScript is in that the text must be valid XML. That is, any start tags must be correctly paired with end tags.)

The second way to run scripting is to use it as the value for certain attributes.

<text onClick='document.write ( "Hello World!" );'>click me</text>

In this example, the script won't run until the text created by the 'text' tag is clicked. And it'll run every time the text is clicked. We call this sort of script an "interaction", and there are lots of things you can do with them. Here's a simple example that changes the color of the text as you roll over it and roll off of it with a mouse.

<text onClick='document.write ( "Hello World!" );' onRollOver="sS('color', 'red');" onRollOut="sS('color', 'green');">click me</text>

In these two new interactions, the scripts are calling the standard 'sS' function, which is short for 'setStyle'. In fact, you can use 'setStyle' instead of 'sS' if you find that easier to read or remember.


Where to Put It

So far, we've seen that by using the 'script' tag, we can place Frontal Scripting code directly where we want it to run, and we've seen that we can deploy it as an attribute's value to enable interactions. These approaches are fine, but sometimes, especially with longer scripts, these approaches can become hard to read and manage. In cases like this, it's better to use style sheets and external files to place your scripts (that's right, there are three ways to run scripts in Frontal, not two -- you got me).

Here's another example of how Frontal may be used to dynamically generate a document, and implement simple rollover, rollout, and click interactions:

<div style="left: 0px; top: 0px; width: 650px; height: 480px; overflow: hidden; scroll: auto;">
 
    <include rel="inline" src="images.xml" />
</div>
 
<style><![CDATA[
    img
        {
            @onRollOver { sS ( "brightness", 100 ); }
            @onRollOut { sS ( "brightness", 0 ); }
            @onClick { destroy ( ); }
        }
]]></style>

This example assumes that the following is the content of the file 'images.xml':

<script><![CDATA[
    for ( var i = 1; i <= 10; i++ )
    {
        document.write ( "<img src='http://frontalcode.com/assets/images/image_" + i + ".jpg' />", parent );
    }
]]></script>

The way to read this example is to replace the 'include' element with the contents of 'images.xml'. That is, with the include tag, and particularly when the 'rel' attribute is set to 'inline', we can pull any external content (in this case a script) into our Frontal document. This approach is a very convenient way to pull a script library into your document.

So, looking at the example as a whole, we again are using 'document.write' to alter our document. But note that we're using a "for loop" to call the function 10 times -- each time with a slightly different value. The result here is that we're loading 10 different images. You can see how a little bit of scripting can have a big result!

We're also using 'sS' again to provide interactions on our dynamically created images. This time, though, we aren't adding the interactions directly to the img tag itself. Instead, we're showing the other place where we can add scripts to our document -- a style sheet. Unlike HTML/CSS style sheets, Frontal Style Sheets can manipulate attributes -- this is done by using the "@" operator. So in this example, we've created a "rule set" with the selector 'img'. This means that any 'img' tag in this document will have this rule set's declarations applied to it. In this case, we have three declarations and all with the "@" operator. So in effect, this rule set is telling the Frontal renderer to add these three attributes to every 'img' tag in the document. The value to add for each attribute is delimited by curly braces. In other words, this rule set is equivalent to replacing all the 'img' tags in the document with this:

<img onRollOver='sS ( "brightness", 100 );' onRollOut='sS ( "brightness", 0 );' onClick="destroy ( );" />

You can imagine how messy it'd be if you had to add those attributes to all 'img' tags by hand. You can also imagine how annoying it'd be to make a change that would require you to edit all of those attributes! And one other thing the astute reader will have noticed -- when we use style sheets for our interactions, we don't have to play all the games with single quotes, double quotes, '&apos;' and '"' that are necessary when applying values to attributes directly. So using style sheets to apply your scripts can be a real lifesaver. For more details, see the section on the 'style' tag.

Elements of the Scripting Language

Frontal's scripting language is based on the same standard (ECMA-262) that JavaScript uses and that's at the heart of ActionScript 2. And ActionScript 3 is based on a superset of ECMA-262. So, any references regarding the basics of these languages are directly applicable to Frontal.

Just to spell this out a bit more, let's quickly look at what Frontal's scripting language provides.

Note that to run the following examples in the Workspace, be sure to wrap them with the 'script' tag.

Statements

The language is written out in "statements". Statements are to a programming language as sentences are to a written language. Here's a statement:

document.write ( "Hello, World!" );

Comments

We add comments to a script to make it easier to understand. There are two forms of comments. The first uses the '//' operator which says that it and anything that follows it should be ignored when interpreting the code. (The process of taking the actions described by a Frontal script is called "interpretation" and it is done by an "interpreter.")

document.write ( "Hello, World!" ); // Write a greeting to the globe.

The other form uses two operators that act kind of like tags in Frontal's markup language. These are "/*" and "*/". With these, everything that comes between them is ignored by the interpreter:

document.write ( "Hello, World!" ); /* This is writing a greeting to globe saying hello to the world */

Variables

A variable is a symbol that we invent to hold a value. So here we're inventing a symbol named 'x' and giving it a value of 5. And because it's variable, we can change its value. So after the second statement completes, symbol 'x' will contain the value 6 because we've added 1 to it.

var x = 5;
x = x + 1;

There are a few rules to remember with variables:

  • Their names (as with all Frontal Scripting elements) are case sensitive. So the variable 'x' is completely unrelated to a variable named 'X'.
  • Variable names must start with a letter or an underscore, and then may include any combination of letters, numbers or underscores.

Operators

We use operators to act on values and variables. So far we've seen the '=' operator which is used to assign a value to a variable. We've also seen the '+' operator which is used to add two numbers or to concatenate two strings. The mathematical operators are:

  • + to add
  • - to subtract
  • / to divide
  • * to multiply
  •  % to do modulo arithmetic
  • ++ to increment a number by one
  • -- to decrement a number by one
  • << to do a bitwise shift left
  • >> to do a bitwise shift right
  • <<< to do an unsigned bitwise shift left
  • >>> to do an unsigned bitwise shift right
  • & to do a bitwise "and"
  • | to do a bitwise "or"
  • ~ to do a bitwise "not"
  • ^ to do a bitwise "xor"
  • "as" to force the treatment of an object reference as a particular class

For example:

x + y - 5
x * y / 10

There are also operators to do assignments:

  • =
  • += to add and assign, e.g., if x = 5, then x += 4 sets x to 9.
  • -= to subtract and assign
  • *= to multiply and assign
  • /= to divide and assign
  •  %= to do modulo arithmetic and assign
  • <<= to do a bitwise shift left and assign
  • >>= to do a bitwise shift right and assign
  • <<<= to do an unsigned bitwise shift left and assign
  • >>>= to do an unsigned bitwise shift right and assign
  • &= to do a bitwise "and" and assign
  • |= to do a bitwise "or" and assign
  • ~= to do a bitwise "not" and assign
  • ^= to do a bitwise "xor" and assign

For example:

x = 5;
x /= 2;
x += .5;
x %= 2;

There are comparison operators that evaluate to true or false:

  • == to check equality
  • === to check exact equality (sometimes things are equal after internal conversions but not with this operator)
  •  != to check inequality
  •  !== to check strict inequality
  • > to check if something is greater than something
  • < to check if something is less than something
  • >= to check if something is greater than or equal to something
  • <= to check if something is less than or equal to something
  • "is" to check if an object reference is of a particular class

The most common use of comparison operators is in conditional statements like so:

if ( x > 10 ) x = 10;

There are logical operators:

  • && to check if two things are true
  • || to check if one of two things are true
  •  ! to invert a true or false value

For example:

if ( x < y && y < z ) document.write ( "x is less than z" );

There is the zany but useful conditional operator:

  • condition ? expresion1 : expression2

This operator returns the value of expression1 if condition is true, otherwise the value of expression2. For example, this would cap the value of x at 10:

x = x > 10 ? 10 : x;

Conditional Statements

Conditional statements allow you to take different actions based on the current state of things. There are various formats they may take, in general:

  • if ( condition ) { statements1 }
  • if ( condition ) { statements1 } else { statements2 }

In both cases, these will perform 'statements1' if the condition is true. In the second case, 'statements2' will be performed if condition is false.

In both cases, if the statements block is exactly one statement, then the surrounding braces are not needed:

if ( rings >= 5 ) 
    document.write ( "one for the thumb" );
else
{
    practice ( );
    practice ( );
    practice ( );
}

Just be careful that by leaving off the braces, you aren't compromising the readability of your script. (A lack of readability often results in scripting bugs in this particular case.)

And finally, with the if-else statement, you may chain them together as much as you like:

document.write ( "Mary just had " );
if ( babies == 1 )
{
    document.write ( "a baby!" );
}
else if ( babies == 2 )
{
    document.write ( "twins!!" );
}
else if ( babies == 3 )
{
    document.write ( "triplets?!" );
}
else
{
    document.write ( "a notion to hire a nanny." );
}

There's also the 'switch' statement to do something similar:

  • switch ( value ) { case value1: statements1; break; ... }

This would allow us to rewrite the example above as:

document.write ( "Mary just had " );
switch ( babies )
{
    case 1: 
        document.write ( "a baby!" );
        break;
    case 2: 
        document.write ( "twins!!" );
        break;
    case 3: 
        document.write ( "triplets?!" );
        break;
    default: 
        document.write ( "a notion to hire a nanny." );
        break;
}

Functions

It can get very tiring writing the same code over and over, and the solution to that is to use functions. A function looks like this:

  • function functionName ( parameter0, parameter1, ... ) { statements; }

The "..." notation indicates that there may be as many parameters in your function declaration as you like. (Note that Frontal's scripting language does not support the ActionScript 3 '...(rest)' parameter.) This statement creates a variable named functionName whose value is rather special because you can "call" it from your script. To call it, you would write:

functionName ( argument0, argument1, ... );

So for example, this function returns the maximum of three numbers.

function maxThree ( x, y, z )
{
    var result = x > y ? x : y;
    result = result > z ? result : z;
    return result;
}
 
var most = maxThree ( 5, 8, 2 ); // Sets most equal to 8.

Note that a function defined in Frontal's scripting language may be called from Flash's AS3 runtime. This is important as it allows us to interface our interpreted scripting environment with Flash's compiled runtime. For example, as you can see in the Code Cookbook, it's possible to use scripted functions to receive callbacks from the Brightcove Media APIs and from Google Map APIs. While Frontal hides much of AS3's complexity in terms of handling interactions, we give this raw example just to show how a scripted function may be called from the Flash runtime:

<text id="test">click me</text>
<script><![CDATA[
    gE ( "test" ).movie.addEventListener ( flash.events.MouseEvent.CLICK, onClick );
    function onClick ( event )
    {
        document.write ( "i've been clicked!" );
    }
]]></script>

And here's the more Frontal way to write this example:

<style><![CDATA[
    #test
        {
            @onClick { document.write ( "i've been clicked!" ); }
        }
]]></style>
<text id="test">click me</text>

Loops

There are severals kinds of loops in Frontal's scripting language. First there is the 'for' loop:

  • for ( variableInitialization; condition; iterator ) { statements }

The most typical example of this sort of loop looks like this:

for ( var i = 0; i < 10; i++ ) { document.write ( i ); }

This will print out numbers from 0 to 9.

The 'for' loop also has this variation:

  • for ( variable in object ) { statements }

With this format, we can step through the keys of an enumerable object. For example, an object or associate array is an enumerable object:

var wishlistPurchaseRecord = { 
    pony: false,
    xbox: true,
    mileyTickets: false
};
for ( var item in wishlistPurchaseRecord )
{
    if ( ! wishlistPurchaseRecord [ item ] ) document.write ( item + ", need it" );
}

And the 'for' loop may also take this convenient format taken from AS3:

  • for each ( variable in object ) { statements }

With this format, we can step through the values of an enumerable object.

var colors = [ 'red', 'white', 'blue' ];
for each ( var color in colors ) document.write ( color );

Another kind of loop is the 'while' loop, which comes in two variants:

  • while ( condition ) { statements }
  • do { statements } while ( condition );

For example:

x = 0;
while ( x < 10 ); {
    x++;
    document.write ( x );
} while ( x < 10 );

and:

x = 0;
do {
    x++;
    document.write ( x );
} while ( x < 10 );

In the statements of any of these loop examples, there are two statements that often come in handy:

  • break
  • continue

'break' will stop the loop immediately and continue running any scripts after the loop. And 'continue' will stop the current loop iteration immediately and go to the next one. So for example:

for ( var i = 100; i < 200; i++ )
{
    if ( i % 2 == 0 ) continue; // skip even numbers
    var isPrime = true;
    for ( var j = 3; j < i / 2; j++ )
    {
        if ( i / j == Math.floor ( i / j ) ) 
        {
            isPrime = false;
            break;
        }
    }
    if ( isPrime ) break;
}
document.write ( i + " is a prime greater than 100" );


Differences with JavaScript

There are some differences between Frontal's scripting language and JavaScript's. These include:

  • No support for regular expression literals. Instead, use the 'RegExp' class. That is, instead of this:
var re = /^(.*)$/g;

Use this:

var re = new RegExp ( "^(.*)$", "g" );
  • The built-in classes like Math, Date, String, etc. use the Flash AS3 classes, and so may be somewhat different. Please consult Flash AS3's documentation.
  • No support for labels.

Differences with Flash ActionScript

Frontal's scripting language is based on the ECMA-262 standard, so it's structure is similar to AS2, which is also based on that standard. However, Frontal harnesses a number of AS3 functions and approaches. The primary differences are:

  • No support for packages and classes, though prototype-based classes are supported. (See Advanced Topics for more details.)
  • Variable types and function return types like the following are allowed but are ignored.
var x : Number = 5;
var y = function ( ) : Number { return 5; }
  • No support for E4X. The Flash ActionScript XML classes are available though, and may be used as long as they do not rely on E4X syntaxes.
  • No support for labels.
  • try..catch..finally only supports a single catch block as defined by the ECMA-262 standard. (ActionScript3 supports multiple catch blocks that are executed only if the exception matches the catch block's error type.)


Personal tools
Get Adobe Flash player