ActionScript 3 Tip of the Day

ActionScript 3 is the next step forward in Flash scripting and to help with the transition (for those of you deciding to make it), I thought I’d make a new Tip of the Day thread for ActionScript 3.0 to help people prepare (after 100 tips, they will no longer be provided daily).

Note: Many of these tips were created prior to the release of Flash and pertain to AS-only projects. Others were for use with the Alpha version of Flash (released prior to the full release of Flash). Most of these are noted as being for “Flash 9”. Though much has changed in Flash CS3, most of those tips should still apply to it as well.

To code AS3, you’ll need one of the following:
[list][]Flash Professional CS3
[
]Free Flex SDK (with AS3 compiler)
[]Flex Builder 2
[
]http://try.flex.org/ (online Flex MXML - with AS3 - compiler)[/list]

[size=+2]ActionScript 3 Tips and Tricks:[/size]

[size=+1][color=red]Latest Additions[/color][/size]
(All categories are ordered from oldest (top) to newest (bottom))
[list]
[] [post=“2129545”]Use IEventDispatcher to type EventDispatcher objects[/post]
[
] [post=“2129547”]What removeMovieClip() becomes in ActionScript 3[/post]
[] [post=“2129548”]How stage, root, and MainTimeline Fit Together[/post]
[
] [post=“2167721”]Thinking “Outside Looking In” and not “Inside Looking Out”[/post]
[/list]

[size=+1]General[/size]
[list]
[] [post=“1876826”]Change the frame rate of your movie[/post]
[
] [post=“1892533”]Abstract Classes[/post]
[] [post=“1897368”]Deep Object Copies with ByteArray[/post]
[
] [post=“1902564”]Determine Instance Class or Superclass[/post]
[] [post=“1907433”]Multiple Arguments in trace()[/post]
[
] [post=“1910480”]Loading Text and XML with URLLoader[/post]
[] [post=“1916345”]Get Sound Spectrum Information[/post]
[
] [post=“1918265”]Garbage Collection: Reference Counting & Mark and Sweep[/post]
[] [post=“1919956”]Weak References[/post]
[
] [post=“1932909”]MXMLC: SWF Metadata Tag[/post]
[] [post=“1942162”]TextField.appendText()[/post]
[
] [post=“1952513”]Access to stage and root[/post]
[] [post=“1955201”]No More Color Class; Use ColorTransform[/post]
[
] [post=“1959977”]Array.indexOf (Array.lastIndexOf())[/post]
[] [post=“1962332”]System.totalMemory[/post]
[
] [post=“1964168”]Closing Net Connections[/post]
[] [post=“1964550”]AVM2 (AS3) to AVM1 (AS2/AS1) Communication via LocalConnection[/post]
[
] [post=“2098266”]Class member enumeration[/post]
[] [post=“2098269”]Key.isDown in AS3[/post]
[
] [post=“2098270”]Scale and Alpha Ranges[/post]
[] [post=“2108579”]Available ActionScript packages[/post]
[
] [post=“2108582”]Numeric Calculations: Number vs. int Speed[/post]
[] [post=“2110830”]Getting Around globally accessible _root and _global[/post]
[
] [post=“2110832”]ActionScript 2 to ActionScript 3 Converter[/post]
[] [post=“2110835”]Accessing FlashVars and HTML Parameters[/post]
[
] [post=“2110839”]ActionScript Speed Through Typing[/post]
[] [post=“2112822”]LivePreview and the LivePreviewParent class[/post]
[
] [post=“2112824”]Flex Component Kit for Flash CS3[/post]
[] [post=“2120336”]Loading URL encoded Variables[/post]
[
] [post=“2120337”]Interactive Masks[/post]
[] [post=“2120338”]No _lockroot[/post]
[
] [post=“2123133”]Loading a Cross-domain Policy File[/post]
[] [post=“2123134”]Loading External Classes with ApplicationDomain[/post]
[
] [post=“2123135”]Save Memory When Reusing Bitmaps With the Same BitmapData[/post]
[] [post=“2123138”]ActionScript SWFs and Version Compatibility[/post]
[
] [post=“2129545”]Use IEventDispatcher to type EventDispatcher objects[/post]
[] [post=“2129548”]How stage, root, and MainTimeline Fit Together[/post]
[
] [post=“2167721”]Thinking “Outside Looking In” and not “Inside Looking Out”[/post]
[/list]

[size=+1]Language Elements/Behavior and Syntax[/size]
[list]
[] [post=“1877318”]Class scope is now bound to class methods[/post]
[
] [post=“1879470”]New Variable Types[/post]
[] [post=“1881409”]New Import Directive[/post]
[
] [post=“1882881”]Type Casting and the as Operator[/post]
[] [post=“1882892”]Unique Class Variables[/post]
[
] [post=“1884719”]The delete Keyword and Class Members[/post]
[] [post=“1886566”]Label Statements[/post]
[
] [post=“1890449”]Commas in Shorthand Array Definitions[/post]
[] [post=“1890456”]Package Block[/post]
[
] [post=“1890484”]Same-file Helper Classes[/post]
[] [post=“1890503”]Access Attributes[/post]
[
] [post=“1893462”]The override Keyword[/post]
[] [post=“1894555”]Using prototype[/post]
[
] [post=“1897728”]Similarly Named Instance and Static Properties[/post]
[] [post=“1903155”]super() Placement (Now Anywhere)[/post]
[
] [post=“1914650”]is Operator (vs instanceof)[/post]
[] [post=“1918059”]Number() Conversion No Longer Interprets Octals[/post]
[
] [post=“1922443”]Changes in typeof[/post]
[] [post=“1923917”]for…in and for each…in[/post]
[
] [post=“1926068”]Default Values for Function Parameters[/post]
[] [post=“1926071”]Undetermined Number of Arguments With …(rest)[/post]
[
] [post=“1926080”]arguments[/post]
[] [post=“1928342”]Support for Namespaces[/post]
[
] [post=“1928343”]Namespaces: Name Qualifier Operator (::)[/post]
[] [post=“1929355”]dynamic is Not Inherited[/post]
[
] [post=“1931779”]Prevent Overriding and Subclassing with final[/post]
[] [post=“1934882”]in Operator[/post]
[
] [post=“1937728”]Constants[/post]
[] [post=“1943280”]include Directive[/post]
[
] [post=“1943292”]Duplicate Variable Definitions[/post]
[] [post=“1954512”]Namespaces: use namespace Directive[/post]
[
] [post=“1959997”]asfunction: Now event:[/post]
[] [post=“2112821”]No more random(); Use Math.random()[/post]
[
] [post=“2120340”]Property Access and Downcasting (parent, root, etc.)[/post]
[/list]

[size=+1]New Classes[/size]
[list]
[] [post=“1886034”]The Dictionary Class[/post]
[
] [post=“1888656”]SimpleButton Instances[/post]
[] [post=“1896981”]Regular Expression (RegExp) Support[/post]
[
] [post=“1899603”]EventDispatcher[/post]
[] [post=“1908351”]URLRequest for URL Strings[/post]
[
] [post=“1910467”]XML vs. XMLDocument[/post]
[] [post=“1964517”]Timer Class[/post]
[
] [post=“1965111”]ByteArray Class[/post]
[] [post=“2108580”]Animator class in AS3 (Flash CS3)[/post]
[
] [post=“2112823”]Loading External SWFs with Loader (Preloading)[/post]
[*] [post=“2123134”]Loading External Classes with ApplicationDomain[/post]
[/list]

[size=+1]Regular Expressions[/size]
[list]
[] [post=“1896981”]Regular Expression (RegExp) Support[/post]
[
] [post=“1914673”]RegExp: Email Validation[/post]
[/list]

[size=+1]Proxy Class[/size]
[list]
[] [post=“1934869”]Proxy Class[/post]
[
] [post=“1934887”]Proxy: getProperty and setProperty[/post]
[] [post=“1939920”]Proxy: callProperty[/post]
[
] [post=“1961524”]Proxy: Property Enumeration (nextName(), nextValue(), and nextNameIndex())[/post]
[/list]

[size=+1]XML[/size]
[list]
[] [post=“1900450”]Writing Inline XML[/post]
[
] [post=“1910467”]XML vs. XMLDocument[/post]
[] [post=“1914704”]XML: @ Operator for Attributes[/post]
[
] [post=“1936562”]XML: XML and XMLList[/post]
[] [post=“1959246”]XML: Children (.) and Decendants (…)[/post]
[
] [post=“2110833”]XML: Removing Nodes[/post]
[/list]

[size=+1]Events[/size]
[list]
[] [post=“1883941”]New MouseMove Behavior[/post]
[
] [post=“1887831”]Detecting When the Mouse Leaves the Movie[/post]
[] [post=“1899603”]EventDispatcher[/post]
[
] [post=“1899698”]Events and Event Types[/post]
[] [post=“1907442”]Calling Event Handlers without Events[/post]
[
] [post=“1914687”]Render Event[/post]
[] [post=“1915416”]Event Propagation Support[/post]
[
] [post=“1948052”]rollOver and rollOut vs. mouseOver and mouseOut[/post]
[] [post=“1931768”]Creating a mouseWithin Event[/post]
[
] [post=“1944595”]mouseEnabled and Event Blocking[/post]
[] [post=“1948039”]mouseChildren with Event Propagation[/post]
[
] [post=“1948087”]Cleaning Up Event Listeners[/post]
[] [post=“1948121”]Event Phases and Event Capturing[/post]
[
] [post=“1948139”]Determining Event Phase[/post]
[] [post=“1948149”]Preventing Event Propagation[/post]
[
] [post=“1948158”]Global Events[/post]
[] [post=“1948182”]Detecting a mouseUp Outside[/post]
[
] [post=“1961593”]Event Capturing and mouseEnabled[/post]
[] [post=“2098265”]Overriding clone in Events[/post]
[
] [post=“2129545”]Use IEventDispatcher to type EventDispatcher objects[/post]
[/list]

[size=+1]Errors and Error Handling[/size]
[list]
[] [post=“1957503”]Runtime Errors; Error Class[/post]
[
] [post=“1957523”]Errors: try…catch…finally and Exception Handling[/post]
[] [post=“1957547”]Errors: Asynchronous Exception Handling[/post]
[
] [post=“2098271”]Errors: Referencing properties from a null reference[/post]
[/list]

[size=+1]Display Objects (MovieClips)[/size]
[list]
[] [post=“1878656”]Graphics Object and the Drawing API[/post]
[
] [post=“1880488”]Display Objects[/post]
[] [post=“1888656”]SimpleButton Instances[/post]
[
] [post=“1897023”]Approach to Depth Sorting[/post]
[] [post=“1905147”]Determining Current Frame Label[/post]
[
] [post=“1923308”]getBounds() vs getRect()[/post]
[] [post=“1939827”]duplicateMovieClip Replacement[/post]
[
] [post=“1939945”]Creating graphics Copies[/post]
[] [post=“1948060”]DisplayObjectContainer contains()[/post]
[
] [post=“1948094”]Detecting Addition to or Removal from Stage[/post]
[] [post=“2108585”]Adding an isPlaying Property to MovieClips[/post]
[
] [post=“2110834”]getObjectsUnderPoint[/post]
[] [post=“2112823”]Loading External SWFs with Loader (Preloading)[/post]
[
] [post=“2113726”]Flash CS3: Frame Navigation and Child Access[/post]
[] [post=“2123135”]Save Memory When Reusing Bitmaps With the Same BitmapData[/post]
[
] [post=“2129547”]What removeMovieClip() becomes in ActionScript 3[/post]
[/list]

[size=+1]Flash Authoring[/size]
[list]
[] [post=“1914661”]Flash 9: Timelines as Classes[/post]
[
] [post=“1921320”]Flash 9: BitmapData and Bitmaps from the Library[/post]
[] [post=“1935107”]Flash 9: Display Object Variables and Instance Names[/post]
[
] [post=“1950401”]Flash 9: Document Class[/post]
[] [post=“1962281”]Flash 9: Strict Mode[/post]
[
] [post=“2098267”]Flash 9: Timeline navigation and code execution[/post]
[] [post=“2098268”]Flash 9: addFrameScript[/post]
[
] [post=“2108583”]Flash CS3: Setting MovieClip Base Classes[/post]
[] [post=“2112820”]Flash CS3: Changing Function Behavior Across Frames[/post]
[
] [post=“2113725”]Flash CS3: New Library BitmapData Instances[/post]
[] [post=“2113726”]Flash CS3: Frame Navigation and Child Access[/post]
[
] [post=“2120339”]Flash CS3: Automatic Timeline Declarations[/post]
[*] [post=“2129549”]Flash CS3: Component Classes[/post]
[/list]

Additional Resources:
[list][]Beginners Guide to Getting Started with AS3 (Without Learning Flex) - uses SDK for MXMLC
[
]Getting Started with ActionScript 3.0 in Adobe Flash CS3
[]ActionScript 3 Language Reference
[
]ActionScript 2 to ActionScript 3 Migration Guide
[]Adobe ActionScript Technology Center
[
]ActionScript 3 Overview
[]ActionScript 3 Learning Tips
[
]ActionScript Cheetsheets and References
[]Programming ActionScript 3 (PDF)
[
]Flash Player 9 Security (PDF)
[*]ActionScript 3 and AVM 2.0 Performance Tuning (PDF)[/list]

Samples:
[list][]Flex 2 AS3 Samples
[
]Flash CS3 Samples[/list]

Edit: Flash 9 Public Alpha doesn’t come packaged with these new classes.

Hi,

I’ve been trying to do some code with the Flash 9 Public Alpha. I’ve come into some trouble using the Sprite class and the new Display package classes in that they do not exist!!

The compiler keeps throwing an error saying that it can’t load the flash.display.Sprite class.

I tried to search for the class and I can’t find it. Does anyone else have this issue? I can use the Sprite type in a FLA doc but not in an AS3 class.

Any help appreciated,

Yep, it sure does come with them; I use them every day. Use:

import flash.display.Sprite;

For more information, see:
http://livedocs.macromedia.com/labs/as3preview/langref/flash/display/package-detail.html
and
http://livedocs.macromedia.com/labs/as3preview/langref/flash/display/Sprite.html

Btw, the Player is in Beta mode, the Flash IDE is in Alpha (not Beta).

~JC

[quote=senocular;1886034]The Dictionary class (flash.utils.Dictionary) in ActionScript 3 is a new addition to ActionScript. Dictionary objects exactly like generic Object objects aside from one thing: Dictionary objects can use any value as a property name or key as opposed to a string.

Generic objects in ActionScript use string keys (names) for property definitions. If a non-string value is used as a key, the key interpretation is the string representation of that value. Example:
ActionScript Code:
[FONT=Courier New][LEFT][COLOR=#000000]var[/COLOR] obj:[COLOR=#0000FF]Object[/COLOR] = [COLOR=#000000]new[/COLOR] [COLOR=#0000FF]Object[/COLOR]COLOR=#000000[/COLOR];
obj[COLOR=#000000][[/COLOR][COLOR=#FF0000]“name”[/COLOR][COLOR=#000000]][/COLOR] = [COLOR=#000080]1[/COLOR]; [COLOR=#808080]// string key “name”[/COLOR]
obj[COLOR=#000000][[/COLOR][COLOR=#000080]1[/COLOR][COLOR=#000000]][/COLOR] = [COLOR=#000080]2[/COLOR]; [COLOR=#808080]// key 1 (converted to “1”)[/COLOR]
obj[COLOR=#000000][[/COLOR][COLOR=#000000]new[/COLOR] [COLOR=#0000FF]Object[/COLOR]COLOR=#000000[/COLOR][COLOR=#000000]][/COLOR] = [COLOR=#000080]3[/COLOR]; [COLOR=#808080]// key new Object() converted to “[object Object]”[/COLOR]

[COLOR=#0000FF]for[/COLOR] [COLOR=#000000]([/COLOR][COLOR=#000000]var[/COLOR] prop:[COLOR=#0000FF]String[/COLOR] [COLOR=#0000FF]in[/COLOR] obj[COLOR=#000000])[/COLOR] [COLOR=#000000]{[/COLOR]
[COLOR=#0000FF]trace[/COLOR]COLOR=#000000[/COLOR]; [COLOR=#808080]// traces: [object Object], 1, name[/COLOR]
[COLOR=#0000FF]trace[/COLOR]COLOR=#000000[/COLOR]; [COLOR=#808080]// traces: 3, 2, 1[/COLOR]
[COLOR=#000000]}[/COLOR]
[/LEFT]
[/FONT]

If you attempt to use different objects as keys in generic objects, what you’ll get iare string conversions that match each other. That means that though you have used separate objects as keys, to the object container, its the same key and they will reference the same value.
ActionScript Code:
[FONT=Courier New][LEFT][COLOR=#000000]var[/COLOR] a:[COLOR=#0000FF]Object[/COLOR] = [COLOR=#000000]new[/COLOR] [COLOR=#0000FF]Object[/COLOR]COLOR=#000000[/COLOR];
[COLOR=#000000]var[/COLOR] b:[COLOR=#0000FF]Object[/COLOR] = [COLOR=#000000]new[/COLOR] [COLOR=#0000FF]Object[/COLOR]COLOR=#000000[/COLOR];

[COLOR=#000000]var[/COLOR] obj:[COLOR=#0000FF]Object[/COLOR] = [COLOR=#000000]new[/COLOR] [COLOR=#0000FF]Object[/COLOR]COLOR=#000000[/COLOR];
obj[COLOR=#000000][[/COLOR]a[COLOR=#000000]][/COLOR] = [COLOR=#000080]1[/COLOR]; [COLOR=#808080]// obj["[object Object]"] = 1;[/COLOR]
obj[COLOR=#000000][[/COLOR]b[COLOR=#000000]][/COLOR] = [COLOR=#000080]2[/COLOR]; [COLOR=#808080]// obj["[object Object]"] = 2;[/COLOR]

[COLOR=#0000FF]for[/COLOR] [COLOR=#000000]([/COLOR][COLOR=#000000]var[/COLOR] prop:[COLOR=#0000FF]String[/COLOR] [COLOR=#0000FF]in[/COLOR] obj[COLOR=#000000])[/COLOR] [COLOR=#000000]{[/COLOR]
[COLOR=#0000FF]trace[/COLOR]COLOR=#000000[/COLOR]; [COLOR=#808080]// traces: [object Object][/COLOR]
[COLOR=#0000FF]trace[/COLOR]COLOR=#000000[/COLOR]; [COLOR=#808080]// traces: 2[/COLOR]
[COLOR=#000000]}[/COLOR]
[/LEFT]
[/FONT]

The Dictionary class is not restricted to this limitation. You can have any value as a key and that value will fully represent that key as opposed to the object using its string representation. So in the above example, if a Dictionary instance is used, you would have two separate keys, one for each object.
ActionScript Code:
[FONT=Courier New][LEFT][COLOR=#0000FF]import[/COLOR] flash.[COLOR=#000080]utils[/COLOR].[COLOR=#000080]Dictionary[/COLOR];

[COLOR=#000000]var[/COLOR] a:[COLOR=#0000FF]Object[/COLOR] = [COLOR=#000000]new[/COLOR] [COLOR=#0000FF]Object[/COLOR]COLOR=#000000[/COLOR];
[COLOR=#000000]var[/COLOR] b:[COLOR=#0000FF]Object[/COLOR] = [COLOR=#000000]new[/COLOR] [COLOR=#0000FF]Object[/COLOR]COLOR=#000000[/COLOR];

[COLOR=#000000]var[/COLOR] dict:Dictionary = [COLOR=#000000]new[/COLOR] DictionaryCOLOR=#000000[/COLOR];
dict[COLOR=#000000][[/COLOR]a[COLOR=#000000]][/COLOR] = [COLOR=#000080]1[/COLOR]; [COLOR=#808080]// dict[a] = 1;[/COLOR]
dict[COLOR=#000000][[/COLOR]b[COLOR=#000000]][/COLOR] = [COLOR=#000080]2[/COLOR]; [COLOR=#808080]// dict** = 2;[/COLOR]

[COLOR=#0000FF]for[/COLOR] [COLOR=#000000]([/COLOR][COLOR=#000000]var[/COLOR] prop:* [COLOR=#0000FF]in[/COLOR] dict[COLOR=#000000])[/COLOR] [COLOR=#000000]{[/COLOR]
[COLOR=#0000FF]trace[/COLOR]COLOR=#000000[/COLOR]; [COLOR=#808080]// traces: [object Object], [object Object][/COLOR]
[COLOR=#0000FF]trace[/COLOR]COLOR=#000000[/COLOR]; [COLOR=#808080]// traces: 1, 2[/COLOR]
[COLOR=#000000]}[/COLOR]
[/LEFT]
[/FONT]

Though you still get [object Object] in the trace, this is a result of the string conversion in the trace command; it is a unique object key in the Dictionary instance.

Note that prop here is typed as *. This is important as the keys in the dict object can be of any type. If you used String for prop’s type, it would cast the a and b objects as Strings when finding them in the loop making prop “[object Object]” instead of actual references to a and b which they would need to be to correctly obtain the values 1 and 2 through dict. For generic objects, regardless of the type used for prop, you will always get a String.[/quote]

Just a follow up on some info about this Dictionary object. It is exactly the same as the Java equivilanet HashMap. The generic object is smaller in size since the key is always a string. HashMap/Dictionary class is generally larger because the object has to contain an actual object instead of a string.

The reason passing an object above won’t work because Object’s toString() function returns [object Object] instead of the memory address (which it really should do instead, like java does). Generally in perfect OO no two objects should have the same toString.

-Danny

Re: For loaded SWFs, the stage properties of its DisplayObject instances will reference the same stage as that referenced in the SWF that loaded it; there can be only one stage. For loaded SWFs, however, the root property will reference that loaded SWF’s root, or its main timleine instance, not the root of the SWF that did the loading.


Are you sure about this? From the loaded swf, I’m seeing its displayObject.stage.url and displayObject.stage.loaderURL both equal to the loaded swf’s info, NOT the loader! The .root properties are the same as well. This is true whether the loaded swf is in the same domain or not. What if the loaded swf is put into a unique ApplicationDomain (in the system domain), as opposed to the same or a child application domain?

Any insight would be incredibly helpful…

[quote=senocular;1964550]The ActionScript virtual machine that runs ActionScript 3 code (AVM2) is completely different from the ActionScript virtual machin that runs ActionScript 1 and ActionScript 2 code (AVM1). Because of this, you cannot call commands in an AVM1 movie from and AVM2 movie or vise versa. The virtual machines just are not compatible in that respect and mostly run in their own kind of shell that allows it to only interact with code being played back in that same virtual machine. What that boils down to is that ActionScript 3 cannot talk to AS1 or AS2 - at least not directly.

One thing these two virtual machines have in common is their implementation of LocalConnection. Both virtual machines deal with local connections in essentially the same way - enough that local connections in AVM1 can receive events from AVM2 and vise versa. So should you come into a situation where you would need a movie published in ActionScript 3 to communicate with a movie published in ActionScript 1 or 2, using local connection is the way to go.

[LIST]
[]LocalConnection AS2
[
]LocalConnection AS3 (flash.net.LocalConnection)
[/LIST]

Example:
ActionScript Code:
[LEFT][COLOR=#808080]// ActionScript 2 file, AS2animation.fla[/COLOR]
[COLOR=#808080]// one movie clip animation named animation_mc on the timeline[/COLOR]

[COLOR=#808080]// local connection instance to receive events[/COLOR]
[COLOR=#000000]var[/COLOR] AVM_lc:[COLOR=#0000FF]LocalConnection[/COLOR] = [COLOR=#000000]new[/COLOR] [COLOR=#0000FF]LocalConnection[/COLOR]COLOR=#000000[/COLOR];

[COLOR=#808080]// stopAnimation event handler[/COLOR]
AVM_lc.[COLOR=#000080]stopAnimation[/COLOR] = [COLOR=#000000]function[/COLOR]COLOR=#000000[/COLOR][COLOR=#000000]{[/COLOR]
    animation_mc.[COLOR=#0000FF]stop[/COLOR]COLOR=#000000[/COLOR];
[COLOR=#000000]}[/COLOR]

[COLOR=#808080]// listen for events for “AVM2toAVM1”[/COLOR]
AVM_lc.[COLOR=#0000FF]connect[/COLOR]COLOR=#000000[/COLOR];
[/LEFT]

ActionScript Code:
[LEFT][COLOR=#808080]*// ActionScript 3 file, AS3Loader.fla*[/COLOR]

[COLOR=#808080]// local connection instance to communicate to AVM1 movie[/COLOR]
[COLOR=#000000]var[/COLOR] AVM_lc:[COLOR=#0000FF]LocalConnection[/COLOR] = [COLOR=#000000]new[/COLOR] [COLOR=#0000FF]LocalConnection[/COLOR]COLOR=#000000[/COLOR];

[COLOR=#808080]// loader loads AVM1 movie[/COLOR]
[COLOR=#000000]var[/COLOR] loader:Loader = [COLOR=#000000]new[/COLOR] LoaderCOLOR=#000000[/COLOR];
loader.[COLOR=#0000FF]load[/COLOR][COLOR=#000000]([/COLOR][COLOR=#000000]new[/COLOR] URLRequestCOLOR=#000000[/COLOR][COLOR=#000000])[/COLOR];
addChildCOLOR=#000000[/COLOR];

[COLOR=#808080]// when AVM1 movie is clicked, call stopPlayback[/COLOR]
loader.[COLOR=#000080]addEventListener[/COLOR][COLOR=#000000]([/COLOR]MouseEvent.[COLOR=#000080]CLICK[/COLOR], stopPlayback[COLOR=#000000])[/COLOR];

[COLOR=#000000]function[/COLOR] stopPlaybackCOLOR=#000000[/COLOR]:[COLOR=#0000FF]void[/COLOR] [COLOR=#000000]{[/COLOR]
    [COLOR=#808080]// send stopAnimation event to “AVM2toAVM1” connection[/COLOR]
    AVM_lc.[COLOR=#0000FF]send[/COLOR][COLOR=#000000]([/COLOR][COLOR=#FF0000]“AVM2toAVM1”[/COLOR], [COLOR=#FF0000]“stopAnimation”[/COLOR][COLOR=#000000])[/COLOR];
[COLOR=#000000]}[/COLOR]
[/LEFT]

The AS3 movie loads the AS2 movie into a Loader instance and places it on the screen. As it plays, the user can click the animation which calls stopPlayback sending the “stopAnimation” event to the local connection named “AVM2toAVM1”. The AS2 movie is then able to receive that event in its stopAnimation event handler and tell the animation_mc clip to stop.[/quote]

I am having a problem with as3 talking to as2 after the initial as2 swf is loaded. Using this example, the first swf comes in and can be controlled just fine. However, if I load a second swf into the AS3 player, it no longer can be controlled. So basically what I need to figure out is how to load multiple as2 swfs into a as3 player. We have a bunch of content which was developed in as2 that we do not want to rewrite at this time. Is there a way to accomplish this.

P.S. The weirdest thing is I put a trace statement in the first as2 swf and after I have unload this clip and loaded the next as2 swf, the trace from the original swf can still be called meaning I believe its removed from the display list but not out of memory. Any clues would be greatly appreciated. I am playing around with gskinner swfbridge right now but haven’t found a solution using this either. Thanks in Advance.

Stat

If my swf file contains a textbox, on some background, how to insert a text message like hello into that text box.

[quote=senocular;2110835]You can pass variables to SWF files in the object/embed code used to display a SWF in HTML. You can do this two ways, one using URL variables (query string) at the end of the SWF path, or through the FlashVars property.

<!-- URL Variables -->
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="640" height="500" align="middle">
    <param name="allowScriptAccess" value="sameDomain" />
    <param name="movie" value="flashMovie.swf?myVar=1" />
    <param name="quality" value="high" />
    <param name="bgcolor" value="#EFF7F6" />
    <embed src="flashMovie.swf?myVar=1" quality="high" bgcolor="#EFF7F6" width="640" height="500" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
<!-- FlashVars -->
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="550" height="400" align="middle">
    <param name="allowScriptAccess" value="sameDomain" />
    <param name="movie" value="flashMovie.swf" />
    <param name="quality" value="high" />
    <param name="bgcolor" value="#FFFFFF" />
    <param name="FlashVars" value="myVar=1" />    
    <embed src="flashMovie.swf" FlashVars="myVar=1" quality="high" bgcolor="#FFFFFF" width="550" height="400" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>

In ActionScript 2, these variables were simply defined as variables in _root. This has changed for ActionScript 3. Now these variables are accessible in a parameters object located in the root loaderInfo object.

Given the HTML embed code above, you would access the myVar property using:
ActionScript Code:
[LEFT]root.[COLOR=#000080]loaderInfo[/COLOR].[COLOR=#000080]parameters[/COLOR].[COLOR=#000080]myVar[/COLOR];
[/LEFT]

[/quote]

Easing Functions in Flash CS3 / Flex 3 SDK

Tutorials on TweenLite or TweenMax often rely on the easing functions that come with the Flash CS3 IDE. These functions are contained in the package fl.motion.easing. All classes under the package name fl are specific to Flash CS3 and are not available in the free Flex 3 SDK. If you use the Flex 3 SDK you have to import your easing functions from the package mx.effects.easing. So any time you see an import statement like this

import fl.motion.easing.;*

you should be able to replace it with

import mx.effects.easing.;*

and get the same functionality.

[quote=senocular;1910480]In previous versions of ActionScript, there were a couple of classes who had the capability of loading external text, namely LoadVars and XML. The loading responsibilities of these classes has moved to one single class in ActionScript 3, URLLoader (flash.net.URLLoader). This class is a lot like LoadVars. The big difference is that it is used for XML since the responsibility of loading XML from an external source has been removed from the XML class. Instead, you would load the text with URLLoader and then give that text to an XML object for parsing.

Like LoadVars, URLLoader has a load() method that is used to load text from an external source. This accepts 1 argument, a URLRequest instance (NOT a URL string). You can then use events from URLLoader to determine when the loading is complete. When complete, the text loaded is available in the data property of URLLoader.

Example:
ActionScript Code:
[LEFT][COLOR=#000000]var[/COLOR] loader:URLLoader;
[COLOR=#808080]// …[/COLOR]
loader = [COLOR=#000000]new[/COLOR] URLLoaderCOLOR=#000000[/COLOR];
loader.[COLOR=#000080]addEventListener[/COLOR][COLOR=#000000]([/COLOR]Event.[COLOR=#000080]COMPLETE[/COLOR], xmlLoaded[COLOR=#000000])[/COLOR];

[COLOR=#000000]var[/COLOR] request:URLRequest = [COLOR=#000000]new[/COLOR] URLRequestCOLOR=#000000[/COLOR];
loader.[COLOR=#0000ff]load[/COLOR]COLOR=#000000[/COLOR];
[COLOR=#808080]//…[/COLOR]
[COLOR=#000000]function[/COLOR] xmlLoadedCOLOR=#000000[/COLOR]:[COLOR=#0000ff]void[/COLOR] [COLOR=#000000]{[/COLOR]
    var myXML:[COLOR=#0000ff]XML[/COLOR] = [COLOR=#000000]new[/COLOR] [COLOR=#0000ff]XML[/COLOR]COLOR=#000000[/COLOR];
    [COLOR=#808080]//…[/COLOR]
[COLOR=#000000]}[/COLOR]
[/LEFT]

[/quote]

What event on URLLoader catches if the file does not load / does not exist?

Found the answer. Using a try/catch was also an option, but this event also works:

IOErrorEvent.IO_ERROR

Hi,

I have a “u” and “v” variables and i do this for example…

var u:URLRequest = new URLRequest(“www.google.com”);
var v:URLVariables = new URLVariables(“q=hehe”);

u.data = v;

trace(u.url);

how do i get it so it will trace “www.google.com?q=hehe

Thanks for the duplicateMovieClip package… As a relatively new AS3 student, can you direct me to an explanation of the options for the – var targetClass:Class = Object(target).constructor; – ? I apprecate that you can not instantiate the DisplayObject class.

In addition, although I have the AS3 Bible for reference, can you suggest other texts? I used Russell Chun’s AS3 book effectively this Semester in my AS3 class.

It’s a good idea to make sure that the stage exists before working with it:

if (stage) 
{
  trace("stageWidth: " + stage.stageWidth + " stageHeight: " + stage.stageHeight);
  stage.frameRate = stage.frameRate + 100;
}

Configuration files often contain Boolean parameters for enabling or disabling features in an application or website. This way non-programmers can easily customize a complex system. But what if someone uses another word than “true” (for example, “1″, “yes”, “y”, “on”)?

In order to make my Flash/Flex apps less error-prone, I usually run all Boolean values from external configuration files through a converter. It’s a simple class with a single static method:

package 
{
   public class BooleanConverter
   {
        
      public static const TRUE_VALUES:Array = [ "1", "true", "yes", "y", "on", "enabled" ];
            
      public static function makeBoolean( val:* ):Boolean
      {
         var str:String = String( val ).toLowerCase();
            
         for ( var i:int = 0; i < BooleanConverter.TRUE_VALUES.length; i++ )
         {
            if ( str == BooleanConverter.TRUE_VALUES* )
            {
               return true;
            }
         }
         return false;            
      }

   }
}

[quote=log2e;2336537]Configuration files often contain Boolean parameters for enabling or disabling features in an application or website. This way non-programmers can easily customize a complex system. But what if someone uses another word than “true” (for example, “1″, “yes”, “y”, “on”)?

In order to make my Flash/Flex apps less error-prone, I usually run all Boolean values from external configuration files through a converter. It’s a simple class with a single static method:

package 
{
   public class BooleanConverter
   {
        
      public static const TRUE_VALUES:Array = [ "1", "true", "yes", "y", "on", "enabled" ];
            
      public static function makeBoolean( val:* ):Boolean
      {
         var str:String = String( val ).toLowerCase();
            
         for ( var i:int = 0; i < BooleanConverter.TRUE_VALUES.length; i++ )
         {
            if ( str == BooleanConverter.TRUE_VALUES* )
            {
               return true;
            }
         }
         return false;            
      }

   }
}

[/quote]

package 
{
   public class BooleanConverter
   {
        
      public static const TRUE_VALUES:Array = [ "1", "true", "yes", "y", "on", "enabled" ];
            
      public static function makeBoolean( val:* ):Boolean
      {
         var str:String = String( val ).toLowerCase();
            
        return (BooleanConverter.TRUE_VALUES.indexOf(str)!=-1)?true:false;
   
      }

   }
}

Thought i would post an optimized version

Hi

I’m currently trying to use a faux-abstract Singleton class to derive a couple of subclasses from.

The Singleton method I’m using is one of the many which uses a static function getInstance() to return the static var holding the singleton instance.

But it seems I’m unable to use getInstance() in the derived classes. I read elsewhere that "static methods and variables don’t exist within the ****inheritance chain of the class in ****AS3".

Is this why I cannot use getInstance() in the derived class? Is there a workaround?

Thanks.

-Nick

[quote=senocular;1893462]Overriding a method of a class means redefining a method for a class which would otherwise be inherited. The new method is then used in place of the inherited one (though the inherited method can still be invoked using super).

For ActionScript 3, when you override a method or property of a superclass, you need to use the override attribute with your new method. This specifies that the member you are creating is overriding that which would otherwise be inherited. If you do not use override with a method that already exists in a superclass, an error is thrown at compile time.

Ex:
ActionScript Code:
[LEFT]package [COLOR=#000000]{[/COLOR]
    import flash.[COLOR=#000080]display[/COLOR].*;
    class MySprite [COLOR=#0000FF]extends[/COLOR] Sprite [COLOR=#000000]{[/COLOR]

        private [COLOR=#000000]var[/COLOR] children:[COLOR=#0000FF]Array[/COLOR] = [COLOR=#000000]new[/COLOR] [COLOR=#0000FF]Array[/COLOR]COLOR=#000000[/COLOR];

        public [COLOR=#000000]function[/COLOR] MySpriteCOLOR=#000000[/COLOR] [COLOR=#000000]{[/COLOR]
        [COLOR=#000000]}[/COLOR]

        public override [COLOR=#000000]function[/COLOR] addChildCOLOR=#000000[/COLOR]:DisplayObject [COLOR=#000000]{[/COLOR]
            children.[COLOR=#0000FF]push[/COLOR]COLOR=#000000[/COLOR];
            super.[COLOR=#000080]addChild[/COLOR]COLOR=#000000[/COLOR];
            return child;
        [COLOR=#000000]}[/COLOR]
    [COLOR=#000000]}[/COLOR]
[COLOR=#000000]}[/COLOR]
[/LEFT]

Since addChild exists in the Sprite superclass, the override attribute is needed to successfully define the new addChild method which also adds the child passed to a children array.

Note that the method signature needs to match that of the overriden method

Override works with both normal class methods as well as getter/setter methods (properties), but it will not work with any of the following:
[LIST]
[]Variables
[
]Constants
[]Static methods
[
]Methods that are not inherited
[]Methods that implement an interface method
[
]Inherited methods that are marked as final in the superclass
[/LIST]

Also be aware that override is not needed for methods inherited directly from the Object class. These include:
[LIST]
[]hasOwnProperty
[
]isPrototypeOf
[]propertyIsEnumerable
[
]setPropertyIsEnumerable
[]toString
[
]valueOf
[/LIST]
These methods are added dynamically and are not part of the actual class definition. The override keyword is to be used only with methods which are part of a class’s original definition.

However, if extending a class which uses a method above as part of its defnition, the override keyword is required. For example, if you are extending Object, you do not need to use the override keyword for the toString method. But, if you extend the Sprite class, you will need to override toString since the Sprite class has its own unique toString which is part of its class definition.[/quote]

Is this why I cannot use getInstance() in the derived class?

Yes.

Is there a workaround?

Yes, just define a new version of getInstance on your subclasses.

Damnit that was the fastest response I’ve ever seen. I was about to go to bed because of this problem, but now… :wink:

Thanks Krilnon!

[quote=Krilnon;2339684]Yes.

Yes, just define a new version of getInstance on your subclasses.[/quote]

The [SWF] metadata tag for AS3.0 has these params:

[SWF
width="#“
height=”#“
widthPercent=”#“
heightPercent=”#“
scriptRecursionLimit=”#“
scriptTimeLimit=”#“
frameRate=”#“
backgroundColor=”#“
pageTitle=”<String>"
]

Please see the comment at the bottom of this page:

http://livedocs.adobe.com/flex/3/html/help.html?content=metadata_3.html

Hi

Is there any way to pass arguments into the document class? I’m guessing no?

-Nick

[QUOTE=senocular;1939827]ActionScript 3 no longer has a duplicateMovieClip method for MovieClip instances (or any DisplayObject instances). Instead, it’s suggested that you just create a new instance of the display object you wish to duplicate using its constructor. This, however, is not the same as duplicateMovieClip, and, really, is more like using AS1 and AS2’s attachMovieClip. For a more accurate representation of duplicateMovieClip in AS3, consider the following function:

package com.senocular.display {
	
	import flash.display.DisplayObject;
	import flash.geom.Rectangle;
	
	/**
	 * duplicateDisplayObject
	 * creates a duplicate of the DisplayObject passed.
	 * similar to duplicateMovieClip in AVM1
	 * @param target the display object to duplicate
	 * @param autoAdd if true, adds the duplicate to the display list
	 * in which target was located
	 * @return a duplicate instance of target
	 */
	public function duplicateDisplayObject(target:DisplayObject, autoAdd:Boolean = false):DisplayObject {
		// create duplicate
		var targetClass:Class = Object(target).constructor;
		var duplicate:DisplayObject = new targetClass();
		
		// duplicate properties
		duplicate.transform = target.transform;
		duplicate.filters = target.filters;
		duplicate.cacheAsBitmap = target.cacheAsBitmap;
		duplicate.opaqueBackground = target.opaqueBackground;
		if (target.scale9Grid) {
			var rect:Rectangle = target.scale9Grid;
			// WAS Flash 9 bug where returned scale9Grid is 20x larger than assigned
			// rect.x /= 20, rect.y /= 20, rect.width /= 20, rect.height /= 20;
			duplicate.scale9Grid = rect;
		}
		
		// add to target parent's display list
		// if autoAdd was provided as true
		if (autoAdd && target.parent) {
			target.parent.addChild(duplicate);
		}
		return duplicate;
	}
}

As you can see, this function (duplicateDisplayObject) takes care of making sure a duplicated instance also retains all the information retained by duplicateMovieClip such as transformation, filters, chaching as bitmap, etc.

Note: There is currently a bug in Flash Player 9 that causes incorrect values to be returned from the scale9Grid property of display objects. This function compensates for that but may need to be edited should this bug be fixed.

Usage:

import com.senocular.display.duplicateDisplayObject;

// create duplicate and assign to newInstance variable
// using true for autoAdd automatically adds the newInstance
// into the display list where myOldSprite is located
var newInstance:Sprite = duplicateDisplayObject(myOldSprite, true);
newInstance.x += 100; // shift to see duplicate

The only thing duplicateMovieClip does that this does not is copy dynamic drawing information. Currently, the graphics object in display objects cannot be duplicated so there is no way to obtain that information for duplicates in duplicateDisplayObject.[/QUOTE]

i’m having problems with this method… i have a movieclip I created on the stage, and I tried using this function on it, but I don’t see any duplicated movieclip…
the code is on the timeline…


var temp:MovieClip = duplicateDisplayObject(mc, true) as MovieClip;
temp.x += 100;

I also tried duplicating a dynamically drawn Sprite (through graphics property), and like what the quote above said, i don’t see anything…