Friday, May 2, 2008

Loading External Content in Actionscript 3 (part 1)

Well... It's been a while since I added to this blog. I went straight from the long healing process of my sinus surgery to being busy teaching and developing. I'm not so much in a slow period. It's more like the calm between two portions of a large storm. Some projects are just ending, while new projects have not gotten into full swing.

I have been saying for a while I wanted to cover a basic technique in Flash CS3 and ActionScript 3. I speak, of course, of loading external content into a Flash file.

By "external content", I mean loading JPGs, GIFs, PNGs and SWFs into the flash file from the web server and not embedding them in the main SWF file.

In AS2, this was done by creating an instance of a MovieClip, and then either loading directly into the MovieClip using loadMovie() or the more powerful MovieClipLoader class (which gave the developer the ability to check the download progress and make progress bars and other preloaders.

ActionScript 3 has added the Loader class which replaces both the loadMovie() method and the MovieClipLoader class. It has removed the need to have an empty MovieClip placed on the stage as a container for loading the images or SWF files.

Here's the Loader's inheritance chain...

Loader > DisplayObjectContainer > InteractiveObject > DisplayObject > EventDispatcher > Object

For those of us non-programmers, this simply means the Loader gains all the properties and methods of the objects in this list. If the DisplayObject has the ability to be added to the stage and made visible, then so does the Loader etc. Because of this we can add the Loader directly to the stage or any other DisplayObjectContainer. (which also includes MovieClips)

Here's our code...

  1. var imageFile:URLRequest = new URLRequest("spry_logo.png");
  2. var myImageLoader:Loader = new Loader();
  3. myImageLoader.load(imageFile);
  4. addChild(myImageLoader);

Line 1 prepares the address of the file to be loaded
Line 2 creates the variable name and the instance of the Loader
Line 3 uses the Loader instance to load the file from the address in the URLRequest
Line 4 adds the Loader (with it's loaded content) into the stage, making it visible as well.

You would then most likely want to move the image into position by adding the x and y coordinates to the Loader instance myImageLoader.

  1. myImageLoader.x = 100;
  2. myImageLoader.y = 150;

If you want to load a new image to replace the old one (say upon clicking a button), you simply change the url of the URLRequest and then reload the loader.

Here is an example of an event handler function that would do this... (this assumes you have a button, and it has added the event listener for the mouse event CLICK)

  1. function onButtonClicked(e:MouseEvent):void
  2. {
  3.    imageFile.url = "flash_logo.png";
  4.    myImageLoader.load(imageFile);
  5. }
This loads in the new file and in theory removes the old file. There is a bit of an issue about this. If you read Grant Skinners post on the topic, you find out that the Flash Player does not unload this content properly (in some situations never). I've noticed this when loading in content with embedded audio. The audio continues playing even when the Loader content has been unloaded.

For small projects this should not prove much of a problem, but if you are planning on loading hundreds of images or complex, memory heavy, SWFs; this technique could start eating into system resources.

Hopefully Adobe changes this sooner than later.

--Rich

Wednesday, March 5, 2008

Communicating with the Browser Using Actionscript 3 (part 2)

Actionscript's ExternalInterface class (again)

In the last ActionScript 3.0 tutorial post I was talking about using ActionScript 3.0's ExternalInterface Class to communicate with the browser. In the previous example I set up the Flash SWF file to use the ExternalInterface.call() method to tell the browser to run a JavaScript function called "gimmeAlert". Nothing fancy, but you can probably think of functions in the browser you would love to run from a Flash menu or button bar.

In this example we will tell flash to expose an ActionScript function so it can be called from the browser using JavaScript.

First we will start with the flash file and HTML we built in the first example. We have already done much of the setup for this example. We have a text field set to "dynamic" and we not only published the Flash file and placed it in the HTML file, but we added the 'id' and 'name' values to the AC_FL_RunContent() function in step 5. This step was not needed to run the previous example, but it is for this one. Flash can run JavaScript without a name or id placed on the object in HTML, but JavaScript needs it to talk back to Flash.

All that done we are ready to have JavaScript run an ActionScript function.

  1. Return to the Flash file and go back to your ActionScript on Frame 1 of the "actions" layer.
  2. At the bottom of that code add a new line and create the following function...

function changeTextBox():void
{
text_txt.text = "You clicked the button in the web page";
}


This is the function we will call from the web page.

  1. At the top of the ActionScript code add the following line...

ExternalInterface.addCallback("changeTextBox", changeTextBox);

The first argument in the addCallback function is the name JavaScript will use to call the ActionScript function. The second argument is the function being called within ActionScript itself. These do not have to match. Here is was just easier to use the same name.

That's it for the ActionScript/Flash end of things. On to the JavaScript/HTML.

In the HTML file we are going to add some very basic browser detection (mainly because the makers of the browsers cannot seem to use the same DOM or Document Object Model). This will ensure your JavaScript is referring to the same object when it tries to talk to the Flash file.
  1. Go to the <script> tag we added to the <head> of the HTML file and add some extra space at the top. Add the following code...

var flashPlayer;

function detectFlashPlayer()
{
if(navigator.appName.indexOf("Microsoft") != -1)
{
flashPlayer = window.eiexample;
} else {
flashPlayer = window.document.eiexample;
}
}


This will make it easier to reference the flash file. If the browser is Microsoft Internet Explorer, then the variable flashPlayer is a shortcut to window.eiexample. If it is any other browser then the variable flashPlayer is a shortcut to window.document.eiexample.

Only two more steps (including testing).

  1. In the HTML file, add a button like you would in a form. You do not need a form tag.
  2. In the button code, add an onclick property with the value flashPlayer.changeTextBox()
Here's the code...

<input type="button" value="Click Me" onclick="flashPlayer.changeTextBox()" />

That's it. Upload everything and test your button. The text in the flash file should change to the text in the ActionScript function. The possibilities are endless. You can have a Flash file change page elements in HTML. You can have HTML forms and navigation send information to the Flash file. You could send messages to a Flash video player that send it to defined que points. Wait... I think YouTube/Google Video already do that with Flash. hmmm.

There is only one piece of bad news. I found this note in the online help files at Adobe.

"Note: Adobe AIR currently does not support the ExternalInterface class."

Update on AIR
I love the Flash community. They tend to share knowledge as quickly as they come by it. It had been a while since I had considered the ExternalInterface Class and the fact that it does not work in AIR. There is good reason for this it turns out. It looks like Flash content in AIR files can call JavaScript as part of the AIR file's DOM. If you are interested in more, check out this blog entry... AIR ActionScript / JavaScript Bridge


For now I am going to assume AIR has some other internal system of communicating between a flash file in AIR and an HTML file in AIR. I only recently learned that you can create links in AIR that open an external browser like IE or Firefox.

I'll post with more info as I find out more.

'till then
--Rich

More: News Of The Nose

The last time I mentioned my sinus issues I had only mentioned having an appointment to see the Otolaryngologist on Jan 29th. A lot has changed since then.
I got an earlier appointment and saw the surgeon on the 10th of January.
He put a scope up my nose and declared that I has a sausage stuffed up there.
We scheduled the surgery for February 7th, with an MRI a week before and another CT the day before the actual surgery.

MRI's by the way... are no fun. Everyone complains about the noise. They gave me earplugs, so that was no big deal. The problems I had were with boredom and pain. The boredom comes from staring at the same spot in a blank white tube for an hour and a half. The pain comes from the fact that I cannot sit still. When I lay down, I was told to get comfortable. I did. Well... sorta. I would have been comfortable if I had been able to move after a minute or so. The point where my head was resting was fine at the start, but after 45 minutes it was hurting pretty good. After 90 minutes it hurt like hell. Same with my neck. What I thought was comfortable turned into a major pain by the end of the process. By the middle of the third battery of tests I kept my head still by making sure the pain in the back of my head and in my neck kept coming from exactly the same places. I was using the pain as registration marks to make sure I was in the right spot. There was no way I was going to move and have to do this over again.

Anyways...

I had my surgery on Feb. 7th and it was mostly uneventful. There is the creepy aspect of being given a drug cocktail where you will be awake, talking, walking and not remember anything. I was not afraid of anything bad happening to me, but it's a creepy idea nonetheless.

After surgery I went home feeling great. I could breath through my nose for the first time in quite a while, and probably due to the drugs I was in almost no pain. Also as Gretchen at work would say... surgery was some of the best sleep I've had in a while. No kidding. I got several hours of uninterrupted sleep. No pain, lots or air, no 3 year old waking me up to sit in the bathroom while she pees. I felt so good, I thought we had just waisted money on pain meds that I would never use.

The first couple days went like that. I would feel fine during the day and take one pain pill every once in a while to reduce the tense feeling in my face and then two when I went to bed to cut what little pain I had and make sleeping easier. This lasted until Monday, Feb. 11th.

That Monday I went in for my first post-op visit. I was under the impression this would be a stick the scope up the nose... "things are looking great" "we'll see you in a couple weeks" sort of visit. I even thought it was silly that we were being driven to the appointment by my mother-in-law. I was wrong.

I did not know the purpose of the first post-op visit was to remove the remainder of the packing, which was behind a great deal of scabs and other post surgical garbage. Even with the numbing spray they used, this was a painful experience (much more than post surgery). There was a moment in the process where I had to take an extended break due to getting light-headed from the pain. If I had known how long I was going to be there and how much it would hurt, I also would have brought along my pain medication.

I spent much of the next week recovering. I had barely used any pain meds before that first visit. After, however, I was using the half dose every 4 hours during the day and the full dose every 4 hours at night.

After a week of this, I was starting to feel some better. Then I went outside. Allaina needed me to make an emergency trip to the store. I did not think the cold would effect me so badly, but between the trip to the store and taking out the garbage in the sub-zero weather, I ended up spending the entire next day in bed.

It has now been almost a month since my surgery and I'm finally getting back to normal. Actually, if I measure normal by how I was before surgery, then I am already much better than normal. I can breath through my nose. I get better sleep (except for having my daughter wake me up at 6:30am whether I am teaching or not). I am a night person. The longer it has been since I taught last, the later I stay up. Then when I teach, I'm up at 5am.

I have another appointment with the ENT on Monday the 10th, so keep your fingers crossed.

'till later
--Rich

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

Monday, January 28, 2008

Cool Firefox Add-On

I bumped into a cool extension/add-on for the Firefox browser the other day.

If you are like me you like your favicons. You know, those icons you see next to the URL in the browser and then in your favorites or bookmarks. I love these things because I can find a link in my favorites much faster by looking for the little icon than I can by reading the text. Right now I'm looking at the orange Blogger.com "B" and I would not mistake it for anything else.

A lot of websites don't have favicons or don't have good ones, or use the same ones for the whole site when I tend to bookmark different areas of larger sites like adobe.com.

The utility I found is Favicon Picker 2 by Robert LaFont, Jr. and can be found in the firefox add-ons list at Mozilla.com or by going directly to https://addons.mozilla.org/en-US/firefox/addon/3176

Once you install this add-on and restart firefox, changing your favicons is incredibly easy. Just go to your bookmarks, right-click on the bookmark you want to change and go to properties. In properties you see a new set of controls allowing you to Erase the favicon or Browse for a new one. Simply choose a 16x16 px gif, jpg, or png file and you now have a new icon for it everywhere your bookmark appears.

Here's one example of how I have used it.

I spend a lot of time going to http://www.adobe.com/devnet which is the Adobe Developer Connection (formerly the Adobe Developer Center formerly the Macromedia Developer's Network, thus devnet). This portion of Adobe's web site has TONS of information on using Dreamweaver, Flash, Flex, ColdFusion and so on, and so on.

Rather than just bookmark the home page and navigate to the particular product or technology I'm interested in, I have bookmarks for each of the product or technology centers. While Adobe has their logo as the favicon for each portion of their site. This does nothing to speed up getting to the topics I want.

I noticed that the Adobe home page now has little icons for many of their products in a list on the left. I used Firefox's Page Info... option found in the Tools menu to grab each of these images. They were all just a little too big, so I fired up Adobe Fireworks CS3 and reduced them the appropriate 16x16px and saved them as nice little Fireworks PNG files.

Now not only can I find my topics faster, My bookmark lists are a lot prettier too. What can I say... I'm a graphics geek.

--Rich

Thursday, January 17, 2008

Hyperlinking in Actionscript 3, a little more.

Oops. I looked over my last post and realized I had forgotten something. This is starting to become a habit. If you look at the last post, I had a line that went...

navigateToURL(myRequest);

This line should read...

navigateToURL(myRequest, "_self");

The extra argument, "_self" is the same as the _self target in an HTML hyperlink. It tells the browser to load the new page in the current browser window and not pop open a new one.

In Actionscript 2, the function...

getURL("http://www.adobe.com");

... did not need a target "window" argument if you wanted "_self". It was assumed.

In Actionscript 3 "_blank" is the assumed target window, so if you are like me and are running Firefox with popup windows turned off... absolutely nothing happens. No link. No warning. Nothing. Don't forget to add a target.

For even more information on navigateToURL(), here's a link to the livedocs help file at Adobe.


--Rich

Sunday, January 6, 2008

Hyperlinking in Actionscript 3


When I first started working with Actionscript 3, I had a list of things I do in Actionscript 2 that I had to be able to do in the new language. Near the top of my list was creating hyperlinks.

In Actionscript 2 creating a hyperlink was one line of code.

getURL("http://www.somesite.com");

place that code somewhere when you wanted to go to a URL and it would work like a charm. If I use it in the MovieClip from my previous post about Events it would look like this...

myClip_mc.onRelease = function():Void
{
getURL("http://www.gotoandlearn.com");
}

In Actionscript 3, the process is only a little more complicated. (once you get past the Event differences)
The new code is in blue and bold.

var myURL:String = "http://www.gotoandlearn.com";
var myRequest:URLRequest = new URLRequest(myURL);

myMovieClip_mc.buttonMode = true;
myMovieClip_mc.addEventListener(MouseEvent.CLICK, doOnClick);

function doOnClick(e:MouseEvent):void
{
navigateToURL(myRequest);
}
for an explanation of the older code see this post... AS3 Event Basics

The first new line of code...
var myURL:String = "http://www.gotoandlearn.com";
..creates a named variable to store our URL address. It is not necessary to store this as a separate variable, but in the long run it is the better practice. I have found that is usually saves me typing, makes my code easier to read, and allows me to change or delete the value more easily.

The next line...
var myRequest:URLRequest = new URLRequest(myURL);
..creates a new URLRequest object in the variable myRequest and passes to the new object the myURL variable we created in the previous line. This code does not create the hyperlink itself. Think of this as just packaging the information about the hyperlink so it is ready for the next piece. There's much more to a hyperlink than just the URL. There are things like the contentType, the method, and the requestHeaders. While all we need for this example is the url, the folks who put together the URLRequest want to give advanced developers more tools to work with.

The last new line...
navigateToURL(myRequest);
...tells the browser to go to the URL (and send along any extra information packaged in the myRequest variable).

That's all we need to have a button or a MovieClip link to a location in the browser. While the basic code may be more than in Actionscript 2, it is set up so advanced developers have more options and the same URLRequest class (object type) can be used in various ways throughout Actionscript.

Speaking of which... I think that will be the topic of an upcoming post. I'll show the basics of using the new Loader class to load external images or swf files.

'till then,
--Rich

[Shameless plug]
Oh, by the way... this is one of the many topics covered in the introductory level Adobe Flash CS3 class at Ascend Training in Deerfield, Illinois and Chicago, Illinois. For the current schedule, go to http://www.ascendtraining.com/schedule.php and click on the name of the class to see it's outline.

Thursday, January 3, 2008

AS3 Events continued...

I realized after re-reading my last post on basic Events in Actionscript 3 , I forgot something important.

In Actionscript 2, the moment you added a mouse event handler like onRelease or OnRollOver, you got the hand cursor, indicating a clickable item.

In Actionscript 3 the hand cursor does not automatically appear when you add a mouse event handler to a movieclip. This will come in handy when you do not want to have your users think of the symbol or MovieClip as being a hyperlink. For example, a dragable item should not look like a hyperlink or a button. Short of changing the appearance of the cursor yourself, you can just leave it as an arrow.

Here's how to add the hand cursor back in.

If you remember how we left our previous code...

myClip_mc.addEventListener(MouseEvent.CLICK, doOnClick);

function doOnClick(e:MouseEvent):void
{
trace(e.currentTarget.name);
}

If you want to make your pointer into a hand cursor, just add this code before the first line.

myClip_mc.buttonMode = true;

You can place this under the first line or at the end of the code, but good practice would dictate placing it at the top.

Our code should now look like this... and we should see that beautiful hand cursor again.

myClip_mc.buttonMode = true;
myClip_mc.addEventListener(MouseEvent.CLICK, doOnClick);

function doOnClick(e:MouseEvent):void
{
trace(e.currentTarget.name);
}

In my next entry I'll show how to link this to a web page.

--Rich

Wednesday, January 2, 2008

Nose News

So here's the word (or words) about my nose. Inverted Papilloma.

My ENT doctor describes the Inverted Papilloma as an aggressively growing, benign tumor. It needs to be removed or I will never be free of this blasted sinus infection. If left in place it has the potential of turning into cancerous lesions. No fun there. I got to look at my CT scan when I was in the ENT's office Even specialists have experts they turn to. My ENT, it turns out, is a specialist on the throat. He is sending me to a specialist on the sinuses and endoscopic sinus surgery.

Turns out this new doctor is the chairperson of the Otolaryngology department at a well known teaching hospital in the area. I hope this means I'll be getting the kind of treatment it sounds like I would be getting. My wife always ends up getting the best doctor
s in their fields. Maybe her luck is rubbing off on me. My appointment is on the 29th. I'm hoping to have this dealt with shortly after that.

--Rich

Tuesday, January 1, 2008

AS3 Event Basics

Part of the goal of my blog is to explain features and techniques using flash/flex and Actionscript 3 (as well as Dreamweaver/HTML/CSS).

I think advanced programmers have plenty of places to turn to for information about Actionscript 3.0, so I plan at this stage to just cover the basics (well slightly beyond that). As a designer who worked a bit with Actionscript 2, I plan to also point out how AS3 differs from AS2.

That being said; let's get started with Actionscript 3.0 Events.

It took me a little while to understand events handling in AS3. My main hangup was the Event object. I was used to thinking of events as verbs not as nouns. I think I get it for the most part at this point. There are a few things I've seen that got a little weird, but that's a topic for a later post.

Event basics...

For those of you who worked with AS2, you were probably accustomed to writing...

myMovieClip_mc.onRelease = function()
{
//do some stuff
}

While this was relatively easy to write, it did not encourage reusable coding and it was just one of many ways to handle events. For example, you had to use a completely different system if you wanted to work with components.

Here's how the same idea would play out in AS3.

myClip_mc.addEventListener(MouseEvent.CLICK, doOnClick);

function doOnClick(e:MouseEvent):void
{
//do something
}


The first line says add an event listener to the myClip_mc MovieClip; which means we are telling it to wait for something to happen and then telling it (the listener) what to do when it does happen. In this case we have told the new listener to wait until the user clicks the myClip_mc MovieClip and in response run the doOnClick function (which we create later).

The next bit of code creates the doOnClick function. Here's the part that used to mess me up. After naming the function we send it (or pass to it) a value/object of the type MouseEvent? What the hell is a MouseEvent! An event is something you wait for or do. It is not an Object that can be handed over, like a baseball or a cat (or all the other examples of objects given in introductory programming classes).

Think of the Event object as a note that is passed along when the event occurs.

The MouseEvent object sends information like what object triggered the event (target or currentTarget), whether a modifier key was held down during the event (ctrlKey or altKey), or where the mouse was on the stage when the event was triggered(stageX and stageY).

While you might not think of uses for all the features of the MouseEvent object, it certainly gives us options to work with.

Imagine you had three buttons that would use basically the same code. Each would use the same function and just test to see what object triggered the event to decide what to do next.

If you want to know which object triggered the event, try adding a trace statement to the function.

trace(e.currentTarget.name);

This will tell you what was clicked that triggered the function.

There will be more about what you can do after events and more about events themselves in future posts.

--Rich