Go Premium for a chance to win a PS4. Enter to Win

x

Adobe Flash

28K

Solutions

13K

Contributors

Adobe Flash (formerly Macromedia Flash) is a cross-platform multimedia and software platform used to embed animations, video, and interactive applications into web pages and desktop and mobile applications and games. Flash displays text, vector and raster graphics to provide animations, video games and applications. It allows streaming of audio and video, and can capture mouse, keyboard, microphone and camera input. The ActionScript programming language allows creation of interactive animations, video games, web applications, desktop applications and mobile applications.

Share tech news, updates, or what's on your mind.

Sign up to Post

I have found that much of my time doing support ends up being a constant repetition of the same steps to different people.  Early on I stated using web pages with Frequently Asked Questions (FAQs) to alleviate most of the burden.  Sometimes this just wasn't enough.  I've played with various different ways of augmenting this over the years and a couple of years back found one solution that topped the rest.

I've tried apps like AviScreenPortable (files were way too large), screencastr (limited time) and screenr (limited time).  The best so far has been Wink by Debugmode.  The tutorial can be as long as you wish, you can add all sorts of elements, including voiceover.  You can also link from either a main menu to other tutorials or from one wink to another.  The end product is in interactive flash (swf file) so although it is extremely small in size it cannot be played on devices like an iPad (can't play flash).

In order to make a wink project you first need to download and install wink from the link above.  I have tested it on windows xp sp2 and 3, windows 2003 r2 server, and windows 7.  Once the program is installed, first start the program you wish to capture, like IE.  Start wink and click the first icon - a blank page, to start a new project.  

Wink Main window
At this point you see the "New Project Wizard"

Wink New Project Wizard
Make sure "Hide Wink Window" is checked then if you wish to only capture the window …
1
 
LVL 30

Author Comment

by:Thomas Zucker-Scharff
Comment Utility
Please note that I do note have any association with wink or it's author.  I am purely a user of the product who is extremely pleased with it.
0
Free Tool: Port Scanner
LVL 11
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

The last time I worked with Flash and Socket connections was in AS1. A recent project required flash connecting to a Socket, and sending receiving information - we figured it would be easy enough - we all know about the socket policy documents and cross domain files, but after much banging head against desk, and googling, it seems this is quite a common stumbling block and I've not found anything that explicitly describes the process (from the Flash side) for someone with little or no experience doing this.

I created a basic socket class that extends the Socket - to handle the specific messages I'm using, including specific heartbearts, and progress events.

The socket is created in C#.

We got to the point where my swf file in the Flash IDE was connecting, sending and receiving as expected - however when running it in the browser it was connecting, disconnecting but never reconnecting.  Usually when I google a problem I'm having, if a lot of results are returned, I usually take that as a good sign, because if many people are having the same problem, the solution must be out there. However, in this case I didn't find it.

We followed the processes in  this Adobe Article
http://www.adobe.com/devnet/flashplayer/articles/socket_policy_files.html

In very layman terms, this is how I understand the process:

1. Flash calls socket.connect()
2. This sends a <policy-file-request/> followed by a NULL byte to the port where it is requesting a policy file.
Step 2 …
0
While working over numerous projects I often had the requirement for doing a screen capture in AS3.0. Unfortunately I found no "ready made" solutions in google search that suited my requirements. But I did come across some great resources which helped me to develop a component for screen capture, and thought I would share my experience (and code) with you.

With a hope that this will appeal and help someone else out there, I have posted it here:

The Solution :

Below is the Main mxml page developed using Adobe Flash Builder, SDK 4.1, Flash Player version 10.1.0. In this example I am doing a screen capture of the stage.
I have added a video and placed 3 buttons, Record, Stop and Play.
On clicking on the Record button, the recording of the page starts. Once you click on stop, it stops recording.
Then click on Play button to see the recorded version. You may have other things/animations on stage for recording too, I have just tried with an flv.
The recording play is basically bytesArray of an FLV created on run-time. You can save it to your server by passing this binary data to any back-end technology - ASP.Net or PHP, etc.

//Main.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="955" height="600"
addedToStage="onInit();"
frameRate="24" >

     <fx:Script>
<![CDATA[
             import 

Open in new window

4
Introduction

This article is primarily concerned with ActionScript 3 and generally specific to AVM2.  Most suggestions would apply to ActionScript 2 as well, and I've noted those tips that differ between AS2 and AS3.

With the advent of ActionScript 3.0 (hereafter "AS3"), the Flash Player realized significant performance gains.  A few years ago, I ran some performance tests comparing JavaScript to AS2.  ActionScript was noticably slower in every benchmark, usually in the range of 300% or more time required to perform large calculations.  Even animation - Flash's wheelhouse - was slower.  AVM2 and AS3 have changed that, and levelled the playing field to a large degree.

That said, the greatest single contributor to slow performance of Flash applications is poorly written ActionScript.  Below you'll find 20 tips to help you write faster applications.  Please note that the motivation behind each tip is performance, not transparency or best practice.  A performance optimization might directly oppose a best practice, and will very often create opacity in your code.  It's your decision as to what takes priority in your application:  performance, transparency or best practices.

Much of the information presented here will provide only negligible gains as regards performance when used in small-scale code operations.  However, when a developer tweens 3500 raindrops every frame, every line of code needs to be parsed and pared to the sharpest, smallest point possible.
8
 
LVL 19

Author Comment

by:moagrius
Comment Utility
Thanks gingermoleman
0
 

Expert Comment

by:fg-dev
Comment Utility
Thanks a lot. Some performance issues like
for(var i:int=0;i<myArray.length;i++) 

Open in new window

gives me impression that this is dumb AS$ :P
0
I have been doing hardcore actionscripting for some time; and needless to say I have faced a lot of problems in just understanding others' code rather than understanding what the code executes. A programmer's life can become hell when there are a lot of developers working together in a team without a consistent framework for terminology.

Each developer uses his/her own way of coding which adds to the complexity in understanding code rather than what the code actually performs. In such scenarios, a guideline will always help a team to work without getting confused on what others have coded previously. From my experience and learning from different articles, I have tried to set up some coding guidelines for any type of ActionScript projects; these guidelines have helped me in my projects till now. The coding standard will help to streamline the Flash/Flex development structure and will lean to better performance of RIA projects. The coding guidelines should be used by any developer doing ActionScript coding.


Added to the Naming Guidelines Article, here is the list of general guidelines for any type of flash actionscripting projects.
These guidelines do not directly improve in the application performance, but definitely make the code proper, easily readable format and indirectly improves development process.

1.01    Copyright notice
Include a copyright notice at the top of every .as file in the framework. The format for the 2010 code copyright is given below.

Open in new window

1
 
LVL 15

Administrative Comment

by:Eric AKA Netminder
Comment Utility
deepanjandas,

Thank you for your submission. Your article has now been published; congratulations!

ericpete
Page Editor
0
I have been doing hardcore actionscripting for some time; and needless to say I have faced a lot of problems in just understanding others' code rather than understanding what the code executes. A programmer's life can become hell when there are a lot of developers working together in a team without a consistent framework for terminology.

Each developer uses his/her own way of coding which adds to the complexity in understanding code rather than what the code actually performs. In such scenarios, a guideline will always help a team to work without getting confused on what others have coded previously. From my experience and learning from different articles, I have tried to set up some coding guidelines for any type of ActionScript projects; these guidelines have helped me in my projects till now. The coding standard will help to streamline the Flash/Flex development structure and will lean to better performance of RIA projects. The coding guidelines should be used by any developer doing ActionScript coding.

1.01    Package Names
Start them with a lowercase letter and use intercaps for subsequent words: controls, listClasses.

Package names should always be nouns or gerunds (the -ing noun form of a verb), not verbs, adjectives, or adverbs.

A package implementing lots of similar things should have a name which is the plural form of the thing: charts, collections, containers, controls, effects, events, formatters, managers, preloaders, resources, skins, states, styles
0
In my long career of working as an actionscript developer, I had spent sleepless night often working hard to solve some small problems which actually took a lot of my development time; later found out the solutions to be a line or two.

Here are some of the common mistakes and some quick code tricks and snippets I used, which can help other developers avoid sleep-less nights.

Problem/Solution #1
This is an easy mistake to make when new to AS3.
I set up a for loop, to count backwards through an Array. But for some strange reason the loop was never terminating! It was simple, here's the original code:
var i:uint;
for( i=arr.length-1; i>=0; i-- )
{
} 

Open in new window

The mistake was simple, I had set i as a uint, so it could never go below 0, so just had to make i an int. It sounds stupid once you realize it, but it wasted enough of my time!

Problem/Solution #2
Once I needed was a strict abstract class in AS3, again, public only constructors, and the absence of the "abstract" keyword from ActionScript meant a workaround.

package
{
    import flash.utils.getDefinitionByName;
    import flash.utils.getQualifiedClassName;
    
    public class AbstractExample
    {
        public function AbstractExample()
        {
	            if( Class( getDefinitionByName( getQualifiedClassName( this ) ) ) == AbstractExample ) throw new Error( 'AbstractExample must be extended' );
	            
	            // rest of constructor here...
	        }      
	    }
	} 

Open in new window


Problem/Solution #3
As class constructors in ActionScript 3.0 must be public, there's not a really clean way to force a class to be a singleton as there is in ActionScript 2.0 or Java say.

Open in new window

0
 
LVL 15

Administrative Comment

by:Eric AKA Netminder
Comment Utility
deepanjandas,

Congratulations! Your article has been published.

ericpete
Page Editor
0
This article describes a solution to a problem of subloading one movie into another when they have different SWF versions.

Sometime back, I was working on an ActionScript project while I came across an interesting fact which I would like to share.  I developed a flash site in AS3.0 but due to some constraints I had to use the home page of another Flash movie developed in AS2.0; so basically I was loading a AVMovie1 movie into another AVMovie2 movie.

I had a Tween created in my home.swf which worked well on first load within AVMovie2. But the problem started when I navigated to another section and again returned to Home. This time, surprisingly, none of the Tweens in home.swf worked!  I checked multiple times to be sure that when I navigated, I cleared my home loader which I added to the base flash movie.

After much debugging, I changed my Tween class to use GreenSock AS2.0 version in home swf. Still the same thing happened; individually the home ran absolutely fine, but when called through the base movie, all the tweens ran perfect only for the first time.

I actually wasted my whole day at it but was lucky enough to get to a solution at the end of the day.

I came to know that when an AS2/AS1-based swf is subloaded into an AS3-based one, then unloaded, and another one is loaded subsequently, a bug in the Flash Player prevents the onEnterFrame from working properly and the _root reference becomes invalid.

The source of my knowledge was …
0
Here are some practices and techniques that can be adopted into your Flash/Flex application development process.

Note: Not all "performance tips" provide an immediately-recognizable benefit.   This article does not include timing validation data, does not cite sources, and does not indicate relative performance gain for each item. Nevertheless, it may be useful as a general guide.  For time-critical operations, I recommend that you set up your own performance tests to verify the accuracy and applicability of these suggestions.

1

Avoid the new operator when creating Arrays.
var a = [];            /// is better than
var a = new Array();

Open in new window

The same applies for creating Objects.

2

The fastest way to copy an array is:
var copy : Array = sourceArray.concat();

Open in new window

3

Use static for properties methods that do not require an object instance.
StringUtils.trim( “text with space at end ” );
Class definition:

package {
public final class StringUtils
{
    public static function trim( s : String ) : String
    {
    var trimmed : String;
    // implementation
    return trimmed;
}}}

Open in new window

4

Use const for properties that will never change throughout the lifecycle of the application.
public const APPLICATION_PUBLISHER : String = “Company, Inc.”;

Open in new window

5

Use final when no subclasses need to be created from a class.
public final class StringUtils

Open in new window

6

The length of method/variable names doesn’t matter in AS3 (true in some other languages).
someVeryLongMethodNameDoesntReallyImpactPerformanceMuch();

Open in new window

7

One line assignments DO NOT buy any performance (true in some other languages).
var i=0; j=10; k=200;   // ... is no faser than if on separate lines

Open in new window

8

There is no difference in memory usage between an if statement and a switch statement:
if ( condition ){
    // handle condition
//--------------------------------------- IDENTICAL MEMORY USAGE:
switch ( condition )
{
    case “A”:
    // logic to handle case A
    break;
    case “B”:
    // logic to handle case B
    break;
}

Open in new window

9

Rank your if statements in order of comparisons most likely to be true
if ( conditionThatHappensAlot ) {
    // logic to handle frequently met condition
} else if ( conditionThatHappensSomtimes ) {
    // handle the case that happens occasionally
} else {
    // handle the case that doesn’t happen that often
}

Open in new window

10

AVM promotes int to Number during calculations inside loops.

11

Use integers for iterations:
(var i: int = 0; i < n; i++)        // is better than...
(var i: Number = 0; i < n; i++)

Open in new window

12

When dealing with indices, use the value -1 to mean “no index”.

13

Locally store function values in for and while
0
Recently, I was asked to recommend a tracking system to be implemented on a clients website.

As the entire site was built on flash, my first thought was to suggest custom built tracking system. However, our company at that point of time didn't have the resource or the expertise to build this. So, we were asked find and review products that would suit this requirement.

One of my first reviews was obviously Google. They have a flash tracking system. However, as comprehensive their product is, so much so in fact, it is complicated. Personally though, I love the way Google handles the tracking system. It's just amazing. However, the company where I was consulting, was not able to implement it.

I was simultaneously reviewing Omniture. They are probably the best in this industry. They had products that suited the requirement. In fact they have product that most likely suits everyones requirement, it proved to be very good and quite flexible. However they are a paid service and the client was not ready to fish out the extra funds for the tracking.

Usually clients want everything for free. Hence my next search was for a flash tracking system that was free. A few hours of search led me to a site called Webeacon. URL - http://www.webeacon.co.cc  Webeacon is a free online system to track events and clicks from flash. I was happy that I found something that would meet the clients minimum requirements and a Free Service.

My client thought the product was fantastic and …
0
Technology Partners: We Want Your Opinion!
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

There are times in your Flash CS4 application when you want more than a simple pointer or a hand, and it's hard to find an ideal walk-through to tell you what to do.  I spent a few days recently learning my way around making custom cursors in Flash, and here are the results.

There are some walkthroughs that tell you how to fake a custom cursor in Flash.  The general idea is to make the default cursor invisible, while attaching event listeners to its movement, and putting a DisplayObject on the stage that is always in the position that the mouse is.

Here is the code I came up with.  I've added liberal comments to explain what's going on in it:

package mypackage 
{ 
        import flash.display.MovieClip; 
        import flash.display.Stage; 
        import flash.events.Event; 
        import flash.events.MouseEvent; 
        import flash.ui.Mouse; 
         
        public class CustomMouse 
        { 
                // define a bunch of constants to be used when setting the cursor.  In this case, these are all 
                // abbreviations for constants I used in production code.
                public static const NORMAL:String = "NORMAL"; 
                public static const AE:String = "AE"; 
                public static const AL:String = "AL"; 
                public static const AP:String = "AP"; 
                public static const AR:String = "AR"; 
                public static const AT:String = "AT"; 
                public static const MD:String

Open in new window

0
Sometimes you know that one object has a specific child in it, but you can't find the child.

This happened to me when I was trying to code some actionScript to make a toolbar work with its embedded buttons.  My partner had created the toolbar using a third party Flash class, and I knew the name of the toolbars and the buttons, but I couldn't access the button.  No syntax I tried would let me get to it.  I tried myToolbar.myButton, myToolbar["myButton"] and myToolbar.getChildByName( "myButton" ), but none of them gave me the button.  getChildByName returned null, which I knew meant that myButton wasn't a child of myToolbar.  Iterating through all the children of myToolbar, all I found were a lot of objects named with "instance" followed by a number.

We checked the work my partner had done.  He had properly named each button, but I wasn't finding it where I thought I would.

To make a long day of research short, it eventually became obvious that the button wasn't an immediate child of the toolbar.  The "instance" names seem to be pretty common to Flash; they are generated frequently in objects designed in Flash.

This question on EE got me pointed in the right direction.  I used the code from ugeb to dump the display lists of myToolbar.  The third-party toolbar software apparently added the button three levels deep.  We started doing a horrible thing - hard-coding to the "instance" variables.  This produced some ugly code:


Open in new window

1
I come across a lot of question about how to access things in the document class from a movieclip, or accessing something from a movieclip in the document class.

It took me a while to figure this out but once I did it makes life so much easier.

By creating a CustomEvent class and placing it in your own utils folder and setting up your AS3 class path, once you import the Custom Event, this is how you'd go about it.

your class would look something like this ...

package whatever.utils //change your package name as required
{
 import flash.events.Event;

    public class CustomEvent extends Event
    {
       
      public static const NOTIFY:String = "notify";
        public var data:*;
            
       public function CustomEvent(type:String, data:*,  bubbles:Boolean = false, cancelable:Boolean = false){
                  super(type, bubbles, cancelable);
            this.data = data;
        }
    }
}

to implement

say you have a nested movieclip that when it hits frame 5 you want to execute a function in the document class called callSomething();

when you add the movieclip in your document class

addChild(nameOfMovieClip);
//add the dispatcher

nameOfMovieClip.addEventListener(CustomEvent.NOTIFY, handleNotifyRoot);

//note the CustomEvent.NOTIFY part - you can add items in your CustomEvent class

Create a handleNotifyRoot method in your document class

function handleNotifyRoot(e:CustomEvent):void
{
trace(e.data.myData.toString());
}

in the movieclip …
2
 
LVL 39

Author Comment

by:blue-genie
Comment Utility
Thanks for your feedback Jakob - much appreciated by all of us I'm sure.
When I first started with AS3 I couldn't figure out how to achieve this and eventually arrived at this solution which worked well for me thus far.  I should have mentioned it's how I do it but not necessarily the best way. Usually in the posts I do that but I was repeating myself so many times that I ended up doing this article.


1. explain #1 to me please
2. the get/set option sounds familiar from my Java days. My OOP knowledge and experience is limited.
3. making data null optional would make this much more generic thus better I agree.
4. why?explain.
0
 
LVL 9

Expert Comment

by:Jakob_E
Comment Utility

Hi Blue-Genie,

The reason why I like the whatever.events namespace structure
is that it matches the one used by flash - making it easier to remember.

import flash.events.Event
import whatever.events.CustomEvent


About the clone and toString overrides:

Event.clone() is used when re-dispatching an event (dispatchEvent(e)). If you don't add
all the properties then the properties of the re-dispatched event won't have the right values
when listeners handle the re-dispatched event. In our case data will be lost.  

An example:
// Add two listeners:
stage.addEventListener(CustomEvent.NOTIFY,firstDispatchHandler,false,0,true)
button.addEventListener(CustomEvent.NOTIFY,secondDispatchHandler,false,0,true)

// Dispatch the CustomEvent on the first                           
stage.dispatchEvent(new CustomEvent(CustomEvent.NOTIFY,{name:"John Doe"}))

private function firstDispatchHandler(e:CustomEvent):void{
    trace("First: "+e.data.name) // traces "John Doe"
    // Re-dispatch event to the second listener
    dispatchEvent(e)
}

private function secondDispatchHandler(e:CustomEvent):void{
    trace("Second: "e.data.name)
    // Without the clone override you'll get an error:
    // TypeError: Error #1034: Type Coercion failed: cannot convert
    // flash.events::Event@54122a01 to whatever.events.CustomEvent.
}



Event.toString() is not required but I find it useful when unsure about what properties is
passed thru the event.

If you don't override Event.toString() tracing your CustomEvent will show:
[Event type="notify" bubbles=false cancelable=true eventPhase=2]

When overriding you'll get this:  
[CustomEvent type="notify" data=[object Object] bubbles=false cancelable=true eventPhase=2]
Now we know that the event is a CustomEvent with a data property  (in this case an object).
 
Tracing events becomes even more useful when dealing with more "advanced" types - like the MouseEvent:
[MouseEvent type="mouseOver" bubbles=true cancelable=false eventPhase=2 localX=38 localY=41 stageX=265.95
stageY=123 relatedObject=null ctrlKey=false altKey=false shiftKey=false buttonDown=false delta=0]
 

Hope it makes sense :)

Best,
Jakob E
 

 


0
This is intended to introduce all collision detection principles in flash, their strengths, weaknesses and workarounds. The main method for Collision Detection in flash is using hitTestObject. But unless you'll be pushing rectangular shapes without any rotation into each other, it won't do much work.  It's mainly oriented to flash game developers, but anyone who bumps stuff in flash can find use of it.
 

1. hitTestObject

Simple and Easy     Its strength-it's light and doesn't really require much math and as such is barely noticeable processor-wise. This means you can have many objects using this hitTest-ing at frame rate. It's weakness-it's mostly useless on its own.Let's take a look at some examples.First,let's start with two rectangular shapes and push them together.A new file,two rectangles converted to symbols,given instance names of rect1 and rect2 and a dynamic text field named txt_hit.Frame 1 gets this code:
 
stage.addEventListener(MouseEvent.MOUSE_MOVE, rectMove);
stage.addEventListener(Event.ENTER_FRAME, hitTest);
function rectMove(event:MouseEvent)
{
	rect1.x = mouseX;
	rect1.y = mouseY;
}
function hitTest(event:Event)
{
	if(rect1.hitTestObject(rect2))
	{
		txt_hit.text = "HIT!";
	}
	else
	{
		txt_hit.text = "";
	}
}

Open in new window

    Perfect hitTest-ing! If you test the movie you can see it detects collision like a charm!
hitTest rectangles     But what if you rotate the rectangles or replace them with circles or any other irregular shape? Let's try.
hitTest irregular shapes
3
 
LVL 18

Administrative Comment

by:WaterStreet
Comment Utility
Crackpack,

This seems like a quality and useful Article, so I didn't mind going beyond the scope of my usual review, in order to make some helpful comments.


1.  Check the following for typo's or spelling.  (something I always point out)

   "t's mainly oriented to flash game..."
   
   "Depending on how much presion..."
   

Use of the following suggestions is up to you.  I think you have a very interesting and helpful article, but it's "headlines" won't grab as much searcher attention as it could.


2.  See tips to title and first sentence at http://www.experts-exchange.com/articles/Community_Support/Article_Tips/SEO-Tips-for-Articles.html

I suggest deleting the first sentence and rearranging the first paragraph, as follows:

"This is intended to introduce all collision detection principles in flash, their strengths, weaknesses and workarounds. The main method for Collision Detection in flash is using hitTestObject. But unless you'll be pushing rectangular shapes without any rotation into each other, it won't do much work.  It's mainly oriented to flash game developers, but anyone who bumps stuff in flash can find use of it."

If there are there more "key words" you want to insert in the title or first sentence then do so.  For example, do you want use the word "shapes" and say "code examples in the either the title and/or first sentence?

I'm keeping this to Author Review so can edit it.  Let me know when you are ready to go, and I will change it to Published.
0
 
LVL 21

Expert Comment

by:alainbryden
Comment Utility
Great article, but none of your formatting or embeds worked. I'm not sure how it got published already, but all the special tags should be using square brackets, not triangular brackets.
0
I know the transition can be hard. We got used to the ease of use ActionScript 2 had, but honestly, it became problematic later on, especially if designers were involved in the project and found it easy to add code as they saw fit.

So, this article takes the basic operations we all did in AS2 and brings them to AS3.


So what happened to my on(release) or something.onRelease statements?

The on(EVENT) clause was an AS1 relic, but AS2 kept it for backwards functionality. The biggest problem with this is that it made the code appear all over the project and finding it could prove to be a big challenge. The Object.ONEVENT clause proved to be better but people could still define the function afterwards and if it was big enough it could be difficult to read the code.

 
//AS1
on(release) {
    trace(this); //would return _level0.myButton (or _level0.instanceXX if it didn't have a name)
}

Open in new window


//AS2
myButton.onRelease = function() {
    trace(this); //would return something like _level0.myButton
}

Open in new window


For AS3, we need listener objects, the listener objects are "listening" to the object they are assigned to, waiting for them to execute an event. If the listener is expecting a certain type of event, it will fire the function assigned to it.

 
//AS3
myButton.buttonMode = true; //makes the cursor a hand, otherwise it shows the default arrow
myButton.addEventListener(MouseEvent.MOUSE_DOWN, buttonPressed);

function buttonPressed(event:MouseEvent):void {
    trace(event.currentTarget); //returns "[Object MovieClip]"
    trace(event.currentTarget.name); //returns "myButton"
}

Open in new window



Undefined Variables?

AS2 was extremely forgiving. You could not define any variable and the code would still work. This was useful but was also a nightmare when a project grew too much. It's not the case anymore for AS3, where you must define the variable and it's type (although, there's still the wildcard "*" for any type).

 

Open in new window

1
 
LVL 3

Expert Comment

by:mharfouch
Comment Utility
Good article.
0
This is a very simple example to help those of you who are still migrating from AS2 to AS3 understand the redesigned event model in AS3.

In AS2.0, event functions (that is, the function to be performed when an event is fired) were stored as a property of the function's caller. Hence, a "button clicked" function would be accomplished by

 
// AS2.0 code
myButton.onPress = function() {
	trace("button clicked")
};

Open in new window


in AS3.0, however, event functions are stored externally as independent functions, and only event listeners (something that checks to see if an event has happened) are attached to the caller itself.

Therefore, the above code snippet would translate as follows:

 
//AS3.0 code
import flash.events.MouseEvent;
// ...
myButton.addEventListener(MouseEvent.CLICK, clickFunction);

function clickFunction(e:MouseEvent) {
	trace("button clicked");
}

Open in new window


A few notes about this new event model

1: You need to import every type of event you will be calling. A few of the most common events include MouseEvent, TimerEvent, and just plain Event. If you want to play it safe, import flash.events.* (that will import all events).

2: The first parameter of your event function (clickFunction in this case) MUST be the type of event that the function is responding to. Also note that all events subclass Event, so the parameter (e:Event) will always work as long as you have imported Event.

3: Also, keep in mind that regardless of what event triggers the function, the function will ALWAYS be called from where it is defined in the code. That is, if you define a function on the main timeline and add a click listener to a button on the stage, trace(this) will return [object MainTimeline].
1

Adobe Flash

28K

Solutions

13K

Contributors

Adobe Flash (formerly Macromedia Flash) is a cross-platform multimedia and software platform used to embed animations, video, and interactive applications into web pages and desktop and mobile applications and games. Flash displays text, vector and raster graphics to provide animations, video games and applications. It allows streaming of audio and video, and can capture mouse, keyboard, microphone and camera input. The ActionScript programming language allows creation of interactive animations, video games, web applications, desktop applications and mobile applications.