Thursday, February 14, 2008

Communicating with the Browser Using Actionscript 3 (part 1)

Actionscript's ExternalInterface class

I know I keep saying the next topic will be loading external content using Actionscript 3, but I keep getting distracted. I'm still recovering from my sinus surgery and had not planned on writing anything until I could focus a little better. Somewhere between pain and drugs there's a lot of typos. A devigner friend of mine was asking me about different ways Flash communicated with other applications, so I am heading off on a tangent yet again.

In the earliest days of flash, about the only way a flash file communicated with the browser (or anything else for that matter) was as a hyperlink. These days, a Flash file can communicate with the browser, an http server, a streaming server for data or video or audio, with other flash files in the browser, with assets loaded into itself and Flash files to be loaded in the future (using a cookie-like feature called SharedObjects). That is a topic for another time (no pun intended).

One of features in the last couple of Flash versions has been the ExternalInterface class. The ExternalInterface class allows a flash file to run javascript functions in the browser and allows the browser to run Actionscript functions in the flash file, all the while allowing these functions to pass data as arguments much the way you would with any function call.

  1. First we are going to create our Flash file. Add a new text field to the file and make sure it is dynamic. Give it an instance name. I called mine text_txt. I chose a font and made sure to Embed Uppercase, Lowercase, Numerals and Punctuation. Make sure your line type is set for Multiline and because I'm not going to take the time here to decorate the text field, I toggled on the Show Border Around Text button.

  2. Add a button. You can make your own; or if you're lazy like I was you can get one from the common libraries. You'll find them under Window>Common Libraries>Buttons. I chose the rectangle flat grey and deleted the text layer so I could use it as a generic button. Add it to it's own layer just in case you have bigger plans for this file and give it an instance name. Mine was bm_btn, short for browser message. I know. Brilliant, Right? What can I say? I'm on medication.
  3. That's it for the stage.
  4. Add an actions layer; and in the actions for the first frame use the addEventListener() method on the button.
    bm_btn.addEventListener(MouseEvent.CLICK, browserAlert);

    Then add the function mentioned as responding to the CLICK event
    function browserAlert(e:MouseEvent):void
    {
    ExternalInterface.call("gimmeAlert", "Hello Flash");
    }
The call() function has one required argument. The name of the javascript function you are running is written here as a String. After that you can include as many arguments as needed for your javascript function. The function we are going to write will take one String variable, So I am passing in the String, "Hello Flash".

ExternalInterface is a "final" class, which means you cannot extend it in making your own classes. It's two non-inherited Methods, addCallback() and call(), are static methods. This means you do not need to create an instance of the ExternalInterface class to use it's methods. In this way it is much like the Math class. You might create a variable to store a random number generated by Math.random(), but you do not need to create a new Math object in order to use the random() method.

  1. Publish your Flash file and either let flash build the HTML file, or add the SWF file to an HTML file in dreamweaver. I tend to add the flash file through Dreamwever (for several reasons I'll have to save for a later post).
  2. Switch to the code view and find where your Flash file is added. You should see the javascript function AC_FL_RunContent() just before your <object> tag. This is the javascript function Dreamweaver(or Flash) adds to place the swf on the page. It's a bit of an odd function. It uses the arguments passed to it to create the parameters and properties added to the <object> or <embed> tags. The first argument is a parameter name, the second is it's value. They just keep alternating that way. We need to add two(four) more at the end. Find where the parenthesis close at the end of the function and add 'id', 'eiexample', 'name', 'eiexample'. This will add the attributes or parameters id and name, and give them both the value eiexample. That way all the current browsers will be happy.
  3. Lastly we need to add our javascript function. This is the one that is going to be run from within the flash file. We are going to be adding the javascript to the head of the document just to make the process easier. Before the closing </head> tag add this code...
    <script language="javascript">
    function gimmeAlert(someText)
    {
    alert(someText);
    }
    </script>

  4. Upload your flash and HTML files and test. When you click the button in the flash file you should get a browser alert message "Hello Flash". If not, make sure that javascripts are allowed in your browser. If you get the Alert message, then you have successfully gotten flash to run a script through the browser.



Since this has become a very long entry, I'm going to call it part 1 and go over the second half in the next post.

'til then
--Rich

For more information on the ExternalInterface class see Adobe's livedocs entry on the topic...
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html

Monday, February 4, 2008

Adding Symbol instances to the Stage with Actionscript 3

One of the things that should have been on my list of things to learn in Actionscript 3, (but wasn't) was adding symbols from the library to the stage.

They have managed to make this process much easier than in Actionscript 2.

Start by creating a MovieClip you want to place on the stage.
Right-Click (ctrl+click MAC) on the MovieClip in the Library and either go to Properties... or Linkage...
Check the Export For Actionscript box. Notice the two text fields above this checkbox.
Base Class: is the AS3 class or object type. If you are completely new to programming, you can think of classes as blueprints for objects in flash. So, by default, if you make a MovieClip in Flash; it is based on the MovieClip class or blueprint. In later examples I'll be making classes of my own to use here instead of MovieClip. By keeping the Base class: flash.display.MovieClip, you are telling Flash that your new object is based on MovieClip (and will therefore have all the features of the MovieClip)

For this example I have given my symbol the name "Thing". I capitalized it because it is a new class even if I do not choose to further define it. Onward to adding this "Thing" to the stage.

Name an empty Layer "Actions" or something like that. Remove the Thing from the stage and go to the first frame of your Actions layer. Open the Actions panel (F9 or option+F9)

The code is the easiest part...

var theThing:Thing = new Thing();
addChild(theThing);

The variable name is also used as the reference for the object. (at least until you have more than one of them) So, if you need to change the object's properties you now...

theThing.x = 50;
theThing.y = 100;
theThing.alpha = .5;

...and so on.

If you have a child object inside your "Thing" object, you just use dot notation to get to it. For example I have a dynamic text field called text_txt inside the "Thing" symbol . Here's how I can change what it says...

theThing.text_txt.text = "Go Pods!";

One more thing. If you are not planning on using the timeline in your Thing object, change the base class to flash.display.Sprite. While one Sprite vs MovieClip will not add up to much, when you get a couple hundred of these floating around, Sprite will add up to needing fewer system resources, which of course means faster smoother files.

--Rich


Coming up next... using the Loader Class to load images and SWFs.

Current Reading... "The Tommyknockers" by Stephen King and
"Actionscript 3.0 Bible" Roger Braunstein, Mims H. Wright and Joshua J. Noble