View Full Version : ActionScript 3 Tip of the Day
senocular
06-19-2006, 09:02 PM
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:
Flash Professional CS3 (http://www.adobe.com/products/flash)
Free Flex SDK (with AS3 compiler) (http://www.adobe.com/products/flex/sdk/)
Flex Builder 2 (http://www.adobe.com/products/flex/)
http://try.flex.org/ (online Flex MXML - with AS3 - compiler)
ActionScript 3 Tips and Tricks:
Latest Additions
(All categories are ordered from oldest (top) to newest (bottom))
Use IEventDispatcher to type EventDispatcher objects
What removeMovieClip() becomes in ActionScript 3
How stage, root, and MainTimeline Fit Together
Thinking "Outside Looking In" and not "Inside Looking Out"
General
Change the frame rate of your movie
Abstract Classes
Deep Object Copies with ByteArray
Determine Instance Class or Superclass
Multiple Arguments in trace()
Loading Text and XML with URLLoader
Get Sound Spectrum Information
Garbage Collection: Reference Counting & Mark and Sweep
Weak References
MXMLC: SWF Metadata Tag
TextField.appendText()
Access to stage and root
No More Color Class; Use ColorTransform
Array.indexOf (Array.lastIndexOf())
System.totalMemory
Closing Net Connections
AVM2 (AS3) to AVM1 (AS2/AS1) Communication via LocalConnection
Class member enumeration
Key.isDown in AS3
Scale and Alpha Ranges
Available ActionScript packages
Numeric Calculations: Number vs. int Speed
Getting Around globally accessible _root and _global
ActionScript 2 to ActionScript 3 Converter
Accessing FlashVars and HTML Parameters
ActionScript Speed Through Typing
LivePreview and the LivePreviewParent class
Flex Component Kit for Flash CS3
Loading URL encoded Variables
Interactive Masks
No _lockroot
Loading a Cross-domain Policy File
Loading External Classes with ApplicationDomain
Save Memory When Reusing Bitmaps With the Same BitmapData
ActionScript SWFs and Version Compatibility
Use IEventDispatcher to type EventDispatcher objects
How stage, root, and MainTimeline Fit Together
Thinking "Outside Looking In" and not "Inside Looking Out"
Language Elements/Behavior and Syntax
Class scope is now bound to class methods
New Variable Types
New Import Directive
Type Casting and the as Operator
Unique Class Variables
The delete Keyword and Class Members
Label Statements
Commas in Shorthand Array Definitions
Package Block
Same-file Helper Classes
Access Attributes
The override Keyword
Using prototype
Similarly Named Instance and Static Properties
super() Placement (Now Anywhere)
is Operator (vs instanceof)
Number() Conversion No Longer Interprets Octals
Changes in typeof
for..in and for each..in
Default Values for Function Parameters
Undetermined Number of Arguments With ...(rest)
arguments
Support for Namespaces
Namespaces: Name Qualifier Operator (::)
dynamic is Not Inherited
Prevent Overriding and Subclassing with final
in Operator
Constants
include Directive
Duplicate Variable Definitions
Namespaces: use namespace Directive
asfunction: Now event:
No more random(); Use Math.random()
Property Access and Downcasting
New Classes
The Dictionary Class
SimpleButton Instances
Regular Expression (RegExp) Support
EventDispatcher
URLRequest for URL Strings
XML vs. XMLDocument
Timer Class
ByteArray Class
Animator class in AS3 (Flash CS3)
Loading External SWFs with Loader (Preloading)
Loading External Classes with ApplicationDomain
Regular Expressions
Regular Expression (RegExp) Support
RegExp: Email Validation
Proxy Class
Proxy Class
Proxy: getProperty and setProperty
Proxy: callProperty
Proxy: Property Enumeration (nextName(), nextValue(), and nextNameIndex())
XML
Writing Inline XML
XML vs. XMLDocument
XML: @ Operator for Attributes
XML: XML and XMLList
XML: Children (.) and Decendants (..)
XML: Removing Nodes
Events
New MouseMove Behavior
Detecting When the Mouse Leaves the Movie
EventDispatcher
Events and Event Types
Calling Event Handlers without Events
Render Event
Event Propagation Support
rollOver and rollOut vs. mouseOver and mouseOut
Creating a mouseWithin Event
mouseEnabled and Event Blocking
mouseChildren with Event Propagation
Cleaning Up Event Listeners
Event Phases and Event Capturing
Determining Event Phase
Preventing Event Propagation
Global Events
Detecting a mouseUp Outside
Event Capturing and mouseEnabled
Overriding clone in Events
Use IEventDispatcher to type EventDispatcher objects
Errors and Error Handling
Runtime Errors; Error Class
Errors: try..catch..finally and Exception Handling
Errors: Asynchronous Exception Handling
Errors: Referencing properties from a null reference
Display Objects (MovieClips)
Graphics Object and the Drawing API
Display Objects
SimpleButton Instances
Approach to Depth Sorting
Determining Current Frame Label
getBounds() vs getRect()
duplicateMovieClip Replacement
Creating graphics Copies
DisplayObjectContainer contains()
Detecting Addition to or Removal from Stage
Adding an isPlaying Property to MovieClips
getObjectsUnderPoint
Loading External SWFs with Loader (Preloading)
Flash CS3: Frame Navigation and Child Access
Save Memory When Reusing Bitmaps With the Same BitmapData
What removeMovieClip() becomes in ActionScript 3
Flash Authoring
Flash 9: Timelines as Classes
Flash 9: BitmapData and Bitmaps from the Library
Flash 9: Display Object Variables and Instance Names
Flash 9: Document Class
Flash 9: Strict Mode
Flash 9: Timeline navigation and code execution
Flash 9: addFrameScript
Flash CS3: Setting MovieClip Base Classes
Flash CS3: Changing Function Behavior Across Frames
Flash CS3: New Library BitmapData Instances
Flash CS3: Frame Navigation and Child Access
Flash CS3: Automatic Timeline Declarations
Flash CS3: Component Classes
Additional Resources:
Beginners Guide to Getting Started with AS3 (Without Learning Flex) - uses SDK for MXMLC (http://www.senocular.com/flash/tutorials/as3withmxmlc/)
Getting Started with ActionScript 3.0 in Adobe Flash CS3 (http://www.senocular.com/flash/tutorials/as3withflashcs3/)
ActionScript 3 Language Reference (http://www.adobe.com/go/AS3LR/)
ActionScript 2 to ActionScript 3 Migration Guide (http://www.adobe.com/go/AS2toAS3/)
Adobe ActionScript Technology Center (http://www.adobe.com/devnet/actionscript/)
ActionScript 3 Overview (http://www.adobe.com/devnet/actionscript/articles/actionscript3_overview.html)
ActionScript 3 Learning Tips (http://www.adobe.com/devnet/actionscript/articles/actionscript_tips.html)
ActionScript Cheetsheets and References (http://actionscriptcheatsheet.com/blog/quick-referencecheatsheet-for-actionscript-20/)
Programming ActionScript 3 (PDF) (http://www.adobe.com/go/programmingAS3_pdf)
Flash Player 9 Security (PDF) (http://www.adobe.com/devnet/flashplayer/articles/flash_player_9_security.pdf)
ActionScript 3 and AVM 2.0 Performance Tuning (PDF) (http://www.onflex.org/ACDS/AS3TuningInsideAVM2JIT.pdf)
Samples:
Flex 2 AS3 Samples (http://www.adobe.com/go/as3examples)
Flash CS3 Samples (http://www.adobe.com/support/documentation/en/flash/samples/)
senocular
06-19-2006, 09:03 PM
Using ActionScript 3, you can dynamically change the frame rate of your movie using the Stage class.
The Stage class (flash.display.Stage (http://livedocs.macromedia.com/flex/2/langref/flash/display/Stage.html)) is the class assigned to the stage object which is accessible from your main movie sprite/movie clip (or others within the same security sandbox) using the stage property. The stage object has a frameRate property which can contain any value between 0.01 and 1000 and determines the frame rate at which the Flash player plays back your movie. Changing this value lets you change the frame rate at runtime.
// change frame rate to 12 fps:
stage.frameRate = 12;
mathew.er
06-19-2006, 10:08 PM
Nice to have an AS 3 thread. Maybe whole Flex/AS3 forum would be usefull as it seem to spred a lot.
To the stage thing... is "stage" and not "Stage" a typo or do you need to import and instance the Stage to change the framerate? Shouldnt flash.display.Stage.frameRate = 12 do the job then?
REEFˇ
06-19-2006, 10:18 PM
Changing FPS with AS? Isnt this a dream come true?
TheCanadian
06-19-2006, 10:26 PM
Nice to have an AS 3 thread. Maybe whole Flex/AS3 forum would be usefull as it seem to spred a lot.
To the stage thing... is "stage" and not "Stage" a typo or do you need to import and instance the Stage to change the framerate? Shouldnt flash.display.Stage.frameRate = 12 do the job then?
No, in AS3 it has changed - the Stage class is accessed through the stage property of a DisplayObject instance. However, they all reference the same thing I think.
ieatcotten
06-20-2006, 02:33 AM
However, they all reference the same thing I think.
Thats how I understand it.
Inheritance:Stage->DisplayObjectContainer-> InteractiveObject->DisplayObject ->EventDispatcher->Object
The Stage class represents the main drawing area. The Stage represents the entire area where Flash content is shown.
The Stage object is not globally accessible. You need to access it through the stage property of a DisplayObject instance.
http://livedocs.macromedia.com/labs/1/flex20beta3/langref/flash/display/Stage.html
mathew.er
06-20-2006, 03:27 AM
So that example at livedocs makes it pretty clear... "stage" is a global object allowing you to view and change its properties or to register events with it.
package {
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
public class StageExample extends Sprite {
public function StageExample() {
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.addEventListener(Event.ACTIVATE, activateHandler);
stage.addEventListener(Event.RESIZE, resizeHandler);
}
private function activateHandler(event:Event):void {
trace("activateHandler: " + event);
}
private function resizeHandler(event:Event):void {
trace("resizeHandler: " + event);
trace("stageWidth: " + stage.stageWidth + " stageHeight: " + stage.stageHeight);
}
}
}
@fabiopb: Why? Isnt this just a sign, that flash goes on pretty well? If your worried anout the Adobe Flash application itself, then you dont need to be... Flex is just for something else than Flash. It wont also disappear from the Internet as everybody has the plugin, people are used to use it and it still has great potential.
sandeep_cdac200
06-20-2006, 03:34 AM
one more step towards making AS to Java!! Great!!
senocular
06-20-2006, 10:55 AM
one more step towards making AS to Java!! Great!!
There are more steps to come that reinforce this idea ;)
senocular
06-20-2006, 11:12 AM
ActionScript 3 is entirely class-based. When you create classes, you create variables and functions (methods) which relate to and work with that class and instances of that class. Unlike ActionScript 2, methods in ActionScript 3 now retain their class scope when called, even if assigned to another object and called from that object, or if used with Function.call and Function.apply. Example:
package {
import flash.display.Sprite;
public class ClassScope extends Sprite {
public function ClassScope() {
traceThis(); // "Class Instance"
var obj:Object = new Object();
obj.traceThis = traceThis;
obj.traceThis(); // "Class Instance"
traceThis.call(new Sprite()); // "Class Instance"
}
public override function toString():String {
return "Class Instance";
}
public function traceThis():void {
trace(this);
}
}
}
this topic at least should be a sticky !
thx Senocular.
senocular
06-20-2006, 01:28 PM
this topic at least should be a sticky !
thx Senocular.
Since it's every day it won't have problems staying near the top ;)
REEFˇ
06-20-2006, 02:51 PM
A few questions...Whats AS 3.0 for? Is there a new flash coming out?
And PK...why do you believe flash will decline?
senocular
06-20-2006, 02:59 PM
A few questions...Whats AS 3.0 for? Is there a new flash coming out?
ActionScript 3 is the next release of ActionScript that will be supported in Flash Player 9. Flex 2 applications are built using ActionScript 3 and the next version of Flash (code named BLAZE) will support it when it's released some time after Flex. Unlike ActionScript 2, ActionScript 3 uses an entirely new virtual machine providing it with new robust features and increased performance.
More details on available and upcoming products can be found on http://www.adobe.com/ and http://labs.adobe.com/ (where both the Flex 2 beta and Flash Player 9 beta are currently available for download)
andrewfitz
06-21-2006, 02:34 AM
Hey sen, how much work do you think it'll take to convert an AS2 class to a fully optimized AS3? I'm assuming it would take just a few changes to make it work, but an entire rewrite to take advantage of all AS3+F9 features. Have you tried converting any of your classes to 3 yet?
Working with a project that has a few thousand lines of code, it seems like a daunting task. Because there's things like attachMovie that aren't even there anymore, so it's not like easy AS1 to AS2, correct?
senocular
06-21-2006, 01:36 PM
Hey sen, how much work do you think it'll take to convert an AS2 class to a fully optimized AS3? I'm assuming it would take just a few changes to make it work, but an entire rewrite to take advantage of all AS3+F9 features. Have you tried converting any of your classes to 3 yet?
Working with a project that has a few thousand lines of code, it seems like a daunting task. Because there's things like attachMovie that aren't even there anymore, so it's not like easy AS1 to AS2, correct?
It depends. Some conversions aren't that bad. However, with the new scoping behaviors of AS3, there can be some drastic changes. Also, another thing to consider is default values for some variable types. Declared but undefined Number variable instances, for example, are no longer undefined but NaN and to check to see if they have been defined you should use isNaN(myNum) and not myNum == undefined.
There are also a lot of little things that have to be modified, such as adding the package {} block, using the override keyword, and changing all instances of Void to void (and not using void if methods have no arguments).
I've only converted my Path class at this point, and I think that was only (if) a couple hundred lines. It wasn't too bad at all, but I know there are some other classes I think I would fear to convert.
senocular
06-21-2006, 01:50 PM
Like ActionScript 1 and 2, ActionScript 3 also has a drawing API that allows you to draw vector lines and shapes dynamically in movie clips and sprites. With ActionScript 3, however, the drawing API is now used off of an object within display objects (movie clips, sprites, etc.) defined as graphics (flash.display.Graphics (http://livedocs.macromedia.com/flex/2/langref/flash/display/Graphics.html)). This graphics property represents the dynamic drawing layer where drawing API drawings exist. Like before, it is placed below all children of the target object. Also, in ActionScript 3, you have new methods that help you more easily create rectangles, circles, and even rounded rectangles. These include:
drawCircle(x:Number, y:Number, radius:Number):void
drawEllipse(x:Number, y:Number, width:Number, height:Number):void
drawRect(x:Number, y:Number, width:Number, height:Number):void
drawRoundRect(x:Number, y:Number, width:Number, height:Number, ellipseWidth:Number, ellipseHeight:Number):void
Example:
// draw a blue rounded rectangle:
var square:Sprite = new Sprite();
square.graphics.beginFill(0xFF);
square.graphics.drawRoundRect(0, 0, 100, 50, 10, 10);
square.graphics.endFill();
addChild(square);
senocular
06-22-2006, 10:19 AM
ActionScript 3 supports a wide range of variable types including some which were not present in previous versions of ActionScript. Basic types for AS3 include:
Primitive:
Boolean
int
null
Number
String
uint
undefined
Complex:
Object
Array
Date
Error
Function
RegExp
XML
XMLList
Additional types also exist that relate to their classes; ex: Matrix (flash.geom.Matrix), Shape (flash.display.Shape), URLRequest (flash.net.URLRequest), etc.
Things to note:
The special Void type has changed in AS3 to be lowercase (void not Void)
There's a new * type that is used to represent any data type. This should be used instead of ommitting typing information for your variables.
var anything:*;
The XML type is not the same as the XML type in ActionScript 1 and 2. The old XML type (object) is now defined as XMLObject. XML now references the new E4X-based XML object.
int and uint are new primitive number data types for integer (numbers without decimal values) and unsigned integer (numbers without decimal values that also cannot be negative). These can be useful for values which are not supposed to have decimal values such as loop iterators. The int data type will provide a small perfomance boost when used over Number in most cases, but uint should only be used when necessary such as with color values.
senocular
06-23-2006, 10:24 AM
ActionScript 3 now has a new collection of "display objects" which includes those objects that can be seen on the screen or added to the "display list." This goes beyond the simple movie clip, button, and text field objects that ActionScript had access to before. AS3 display objects include
AVM1Movie
Bitmap
Loader
MorphShape*
MovieClip
Shape
SimpleButton
Sprite
StaticText*
TextField
Video
*Are for referencing pre-existing objects existing on the timeline; you cannot create them via AS.
AVM1Movie represents a movie created with ActionScript 1 or 2. Those movies use ActionScript Virtual Maching 1 where AS3 movies use AVM2. AVM2 movies can play AVM1 movies, but cannot interact with them (their ActionScript) using AS3.
Bitmaps are bitmap objects. You can specify their imagery with BitmapData objects or they can be bitmaps from files.
Loader objects are display objects that load external content into them. This content can be images or other SWF movies.
MorphShapes are shape tweens created in the timeline. Though you cannot create them in ActionScript, you can access those that exist on the timeline already using ActionScript and they are of the type MorphShape.
MovieClips are the movie clips you know and love.
Shapes are stripped down movie clips that essentially only contain a graphics object for drawing in with the vector drawing API. Using Shapes instead of MovieClips or Sprites can help conserve memory
Sprite objects are essentially movie clips without timelines. This is your most common display object in AS3 and usually the one extended when creating your own display object subclasses.
StaticText, like MorphShapes, cannot be created with ActionScript instead referening static text objects that are pre-existing on the Flash timeline.
TextField objects include dynamic and input text.
Video objects represent Flash video.
senocular
06-24-2006, 12:07 PM
The import directive in ActionScript 3 is a little different than import in ActionScript 2. In AS2, import was used solely as a name shortener for classes defined in packages; it was not required to use a class. Instead of using import, you could just have used the class's full name. ex:
// ActionScript 2
var myPoint:flash.geom.Point = new flash.geom.Point(0,0);
In ActionScript 3, the import directive is required to access classes in their packages, even if you reference the class using its full name. You can still use the full name (or just the imported class name), but the import is required
// ActionScript 3
import flash.geom.Point;
var myPoint:flash.geom.Point = new flash.geom.Point(0,0);
As with AS2, you can also use the wildcard character (*) in AS3 to import all classes within a package.
import flash.geom.*;
Krilnon
06-24-2006, 12:36 PM
How did I not see this thread until today? :-/
Why are the rules /suggestions for using uint so strict? Is it not as fast as an int variable? In other words, I see no reason not to use uint for every value that I know will be a positive integer, why isn't this the case?
When using addChild and getChild-type methods, you are allowed to add objects that are subclasses of DisplayObject, but the 'get' functions all return DisplayObjects. I'm assuming that this is done so the method will have only one return type, but it is kind of inconvenient to have to construct subclass-typed objects out of that returned value, like "Bitmap(imageHolder.getChildAt(0))". Is there a better way of handling returns that return value types that are less specific than you would like?
How do you make functions callable by events and non-events with more than just an event as an argument? In your CoilGallery source, I saw that you had something like "event:Event = null", which I'm assuming makes the argument optional. I've been running into trouble using functions for multiple purposes that need specific argument types. If I, for example, had a function that for some reason needed to have the x property of a DisplayObject. If I wanted to be able to call this function with an event and by itself, would it be best to define the function so it can be run by itself and then have a separate function that serves as an event handler to get the desired property using info from the event.target and then passes that into the function with the x argument?
senocular
06-24-2006, 12:54 PM
1. Yes, uints are pretty slow. I don't know why, but they are. Typically they're just used for numbers that require values that high (like colors with alpha information). Using int for integers is generally a little faster than Number (but not much if at all in all situations). All in all, using only Number wouldn't kill you. They might get around to optimizing int (and maybe uint?) more in the future, though. So its good practice to use them where applicable. For more info see:
http://kuwamoto.org/2006/06/15/avoid-ints-in-actionscript/
2. The getChild methods all return DisplayObject types because methods are only allowed to have one type associated with their return value. By using DisplayObject, its using a type that all objects must be or inherit from to even be added in the first place. So if you add something to the display list, you know it's at least going to be a DisplayObject and having the return value typed as that means it works for whatever is returned.
Note: You can also use the 'as' operator to change the type of variables (and I think this is preferred over ClassCast() conversions).
var myBmp:Bitmap = imageHolder.getChildAt(0) as Bitmap;
3. In using event:Event = null as the parameter for a method, I was able to use it both as an event (where the event object is passed) and as a normal method call anywhere else in my code using methodName(); since having a default value for parameters makes them optional. Required parameters have no default value. You can have both as well, but optional have to come after all required.
If you want to have a method that acts as an even handler and a normal method, if its "normal" use doesn't use an event parameter as the first parameter, then you'll most likely just have to use a separate method for the event handler that calls your normal event.
There is also a new ...(rest) parameter that lets you specify an undetermined number of untyped arguments. Arguments that map themselves to the ...(rest) parameter are assigned to an array with the name of (rest) which you can name anything you want. I'm pretty sure I used this for the trace method in the Output class (com.senocular.utils.Output). That should use it by itself as one parameter, but you can also have required parameters come before it. You can find more information in the docs under
Language Elements > Statements, Keywords & Directives > [Definition keyword summary] ...(rest)
Krilnon
06-24-2006, 01:11 PM
Thanks senocular! :beam:
Note: You can also use the 'as' operator to change the type of variables (and I think this is preferred over ClassCast() conversions).
That's just what I was looking for. I had seen the 'as' operator before (in your CoilGallery, I think), but it makes much more sense when applied to a situation that I'm familiar with.
senocular
06-26-2006, 12:12 PM
ActionScript lets you change the assigned type of an object to other compatible types when needed. This is called casting. Both ActionScript 2 and 3 support casting using type(object) syntax. For example, if your custom class object was assigned to a variable typed as an object, you can reassign typing for that object by casting it to have a type of your custom class thereby letting Flash know what methods and properties exactly are available to that object
var obj:Object = getMyCustomObject();
vay customObj:MyClass = MyClass(obj);
ActionScript 3 introduces a new operator for casting, the as operator. The as operator replaces casting using type(object) in ActionScript 2 with a syntax of object as type.
var obj:Object = getMyCustomObject();
vay customObj:MyClass = obj as MyClass;
The as operator works much like casting in ActionScript 2. If the conversion can't be made, the result of the cast is null. Otherwise, the object being cast is returned and assigned a type of the type used.
ActionScript 3 still supports type(object) casting, but the behavior is a little different now. Instead of returning null for failed casting, a TypeError is thrown. Failure occurs when you try to cast an object into an incompatible type such as trying to cast one object into a type it is not associated with or inherits from.
Note: ActionScript also has global conversion functions in that work in the style of Class(object) which have precedence over type(object) casting. These include String(), Number(), and Array(), etc. These don't cast so much as actually convert one object into another (where applicable). Because these have precedence over type(object) casting, its preferred that the as operator be used when casting objects to different data types.
senocular
06-26-2006, 12:23 PM
In ActionScript 2, variables defined within a class's body were defined in the class's prototype object. This was an efficient means to handle variable definitions but it also meant that complex data types (such as Arrays) had a tendency to be "shared" among instances if not explicitly defined for instances within the class constructor. This is no longer a problem with ActionScript 3. Class variables defined in the class body are now unique to each class instance so this problem no longer occurs.
class myClass{
private var list:Array = [1,2,3]; // bad for AS2, ok for AS3
public function myClass(){
// list should be defined here for AS2
}
}
senocular
06-27-2006, 03:09 PM
The mouseMove event has changed a little in ActionScript 3. Before, mouseMove events were global meaning that no matter where the mouse was in the Flash movie, if it moved, any listener to Mouse or any MovieClip (which automatically receive mouse events without being made listeners of Mouse) would recognise that it moved and recieve the event.
With ActionScript 3, the Mouse object is no longer used for dispatching mouse events. For mouseMove events, you would listen to InteractiveObject instances such as Sprites, MovieClips, and the Stage. So instead of adding listeners to Mouse, you would use some InteractiveObject. For each InteractiveObject instance, though, the mouseMove event is only called when the mouse moves from one location on that object to another location on that object. For a mouseMove event anywhere in the movie, you would want to add your listener(s) to the Stage instance.
Given this behavior, when using mouseMove to drag objects, you would always want to use Stage as your dispatcher in the case that when you move the mouse, the location it moves is off the object your dragging. If that were to happen, the mouseMove event wouldnt not fire and your drag would stop.
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragMyObject);
Krilnon
06-27-2006, 05:59 PM
With ActionScript 3, the Mouse object no longer exists
Doesn't it exist, just not in the way it did before? For example, trace(typeof(Mouse)); That traces "object", so Mouse still exists as an object, right? It just has two static methods and everything that it inherits.
As far as dragging goes, has startDrag (and stopDrag) been improved at all? I always avoided it in Flash <9, but I tried to use it again for the AS Battle and ended up falling back on hand coding it with if constraints. The built-in function seems to be more trouble than it's worth, so is there any case where it would be better to use startDrag? (Perhaps when I have a predefined rectangle that might be changed dynamically?)
senocular
06-27-2006, 06:13 PM
Yeah, I meant to say its no longer an object that you add listeners too - lemme edit that ;) Mouse does exist, but for a different reason - mainly just to control whether or not the mouse cursor is seen (I think that actually may be it too)
AS for startDrag, I dont think it has changed much.
JoshuaJonah
06-27-2006, 06:19 PM
ActionScript 1.0 Tip of the day: Upgrade
:D
Krilnon
06-28-2006, 11:19 AM
I have a suggestion for today's hint: Describe how to use AS 3.0 classes with the Flash 9 preview. I'm trying to get my gallery to work with it, though I haven't had any luck so far. (I've only had it for 10 minutes, though)
var myGallery:KrilGallery = new KrilGallery();
Generates: TypeError: Error #1009: Cannot access a property or method of a null object reference.
at KrilGallery$iinit()
at Timeline0_6f3f7df53146e840b3f92ad2f63d7757/::frame1()
It does run the first line of the constructor function, though, as it traces "KrilGallery". The next line tries to access the stage, so perhaps that is part of the issue.
senocular
06-28-2006, 11:34 AM
Krilnon, all you do is type your class in the document class field in the property inspector then publish.
Your application class is setup to represent the actual movie being published (the document class). Just making a new instance of it on the timeline only creates an instance in a default document class and your movie won't function as expected. :)
Krilnon
06-28-2006, 11:57 AM
Oh, that makes things much more simple. Thanks :)
senocular
06-28-2006, 12:11 PM
The delete keyword in Flash is used to remove variable definitions. It doesn't delete objects from memory (this happens behind the scenes using something called the "Garbage Collector"), it just takes a variable you've created and gets rid of it so that it is no longer accessible and is no longer present through iteration (for..in loops, etc.).
Internally, the Garbage Collector, or GC for short, knows when to physicially delete objects in memory when they no longer have any variables that reference them. So, for example, if you have two variables A and B and they both reference ObjectX, deleting variable A will not cause ObjectX to be removed from memory by the GC because variable B still references it. However, if you delete both variables A and B, there will be no more references to ObjectX and the GC will recognize that it needs to be removed from memory
var a:Object = new Object();
var b:Object = a; // reference same new Object();
delete a;
trace(b); // [object Object] - still exists in memory
delete b;
// GC will mark object for deletion from memory
This works practically the same way for Flash 8 and Flash 9 (ActionScript 1, 2, and 3), though some changes were made in 8 to improve the GC. (Note: GC deletion from memory is not immediate.)
Though the GC has not really changed much with ActionScript 3 and the new virtual machine that runs it, what has changed is the behavior of the delete keyword. Now, the delete keyword only works for dynamic properties of a class instance and not declared class memebers (variables or methods). With ActionScript 1 and 2, delete could be used for anything. ActionScript 3 only lets you delete dynamic variables and locks those which are not.
// ActionScript 2
class DeleteVarClass {
public var myVar:Number;
function DeleteVarClass() {
myVar = 1;
trace(myVar); // 1
delete myVar;
trace(myVar); // undefined
}
}
// ActionScript 3
package {
public class DeleteVarClass {
public var myVar:Number;
public function DeleteVarClass() {
myVar = 1;
trace(myVar); // 1
delete myVar;
trace(myVar); // 1
}
}
}
Because myVar in the above example was declared as part of the class definition, it cannot be deleted using delete in ActionScript 3.
Since you cannot delete class members in ActionScript 3, if you want to cause a variable to no longer reference an object or value in memory you should set your variable's value to null instead of deleting it.
myVar = null;
If all variable references to an object are null, the GC will mark it for deletion and it will eventually be cleared from memory.
lunatic
06-28-2006, 12:19 PM
*sigh* I wish I had your brain. :(
senocular
06-29-2006, 03:54 PM
The Dictionary class (flash.utils.Dictionary (http://livedocs.macromedia.com/flex/2/langref/flash/utils/Dictionary.html)) 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:
var obj:Object = new Object();
obj["name"] = 1; // string key "name"
obj[1] = 2; // key 1 (converted to "1")
obj[new Object()] = 3; // key new Object() converted to "[object Object]"
for (var prop:String in obj) {
trace(prop); // traces: [object Object], 1, name
trace(obj[prop]); // traces: 3, 2, 1
}
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.
var a:Object = new Object();
var b:Object = new Object();
var obj:Object = new Object();
obj[a] = 1; // obj["[object Object]"] = 1;
obj[b] = 2; // obj["[object Object]"] = 2;
for (var prop:String in obj) {
trace(prop); // traces: [object Object]
trace(obj[prop]); // traces: 2
}
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.
import flash.utils.Dictionary;
var a:Object = new Object();
var b:Object = new Object();
var dict:Dictionary = new Dictionary();
dict[a] = 1; // dict[a] = 1;
dict[b] = 2; // dict[b] = 2;
for (var prop:* in dict) {
trace(prop); // traces: [object Object], [object Object]
trace(dict[prop]); // traces: 1, 2
}
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.
andrewfitz
06-29-2006, 08:13 PM
What is the point, can't you just use a regular object? I guess I'm confused as to what it would be used for.
senocular
06-29-2006, 08:50 PM
What is the point, can't you just use a regular object? I guess I'm confused as to what it would be used for.
You can look at the examples and see where they are different. Objects use string keys where Dictionaries use the objects themselves. This lets you essentially use objects as variable names which can be very useful in the right circumstances.
For example, consider having a bunch of "male" objects and a bunch of "female" objects, and eventually you have your objects get hitched and all get married. However, male and female objects dont have any internal property that lets you specify who their partner is, so instead you set up a reference table to let you access any female from a male or male from a female so reference[male] = female. Given any male, access it from the reference object and it returns the respective female and vise versa. Here's the thing, using normal objects, this won't work because any male or female you use as a key will be resolved as "[object Object]" and after assigning them all to your reference object, it only ends up with one value, "[object Object]" which has the value of the last male of female you assigned to it. Dictionaries, on the other hand, don't make that string conversion and would work for this.
I even used a dictionary in my coil gallery to allow me to reference sprites added to the coil display. Sprites added using addItem were used with another object with coil-specific properties which was used in how the sprite was displayed in the coil display itself. Using a dictionary object, I could quickly access that wrapper by using a reference to the sprite without the need to modify anything within the sprite itself.
mathew.er
06-29-2006, 10:19 PM
Regarding a post you wrote earlier, I am a little curious about one thing... Why would anyone need * as a type? Isnt
var anything:*;the same asvar anything:Object;as everything comes from the Object class... Or are primitive data types not really objects?
andrewfitz
06-29-2006, 10:43 PM
I don't think Strings or Numbers etc are objects.
senocular
06-29-2006, 10:52 PM
* represents an untyped value. It has more "compatibility" in the sense that it doesn't conflict with other data types. For example, if you return an variable typed as Object from a function and attempt to assign it to a varible typed as Array, you'll get an error. Returning a variable typed as * will not give you that error. Now, since Array is derived from object, you could get around that confliction using the as operator, but if you're possibly dealing with any kind of return type, * might be more convenient. The Proxy class, for example, uses * for values assigned to and retrieved from it.
* is also useful if you want your variables to be able to have a value of undefined. Objects cannot be undefined and are instead null. Using * you can have a variable with a value of undefined.
senocular
06-29-2006, 10:55 PM
I don't think Strings or Numbers etc are objects.
They are Objects as the Number and String classes inherit from the Object class. All classes inherit from Object, and though there are primitive number and string values, in Flash they are still instances of their respective Number and String classes and therefore are seen also as Object instances.
senocular
06-30-2006, 02:18 AM
ActionScript 3 introcuduces labels (http://livedocs.macromedia.com/flex/2/langref/statements.html#label), new identifiers that can be associated with loop blocks. Why would you want to identify a loop block? Because you can use that identifier as a target for break and continue commands. Consider two loops where one is nested in the other. If at some point you want to exit both loops while in the nested loop, you can't. The break command only exits the current block. A common workaround is to use a flag variable to be able to check that, when in the first loop, if that should be exited as well. ex:
var i:Number;
var j:Number;
var exit:Boolean = false;
for (i=0; i<10; i++) {
for (j=0; j<10; j++) {
if (i > 3 && j > 3) {
exit = true;
break;
}
}
if (exit) {
break;
}
}
When i is greater than 3 and j is greater than 3, break is used to exit the current loop, but this only exits the j loop. To exit the i loop too, the exit variable was used with an if condition in the i loop to exit that one as well.
Labels let you identify and break from a specific loop (and consequently any nested loops within). The format for a label is label: statement
Ex:
var i:Number;
var j:Number;
mainLoop: for (i=0; i<10; i++) {
for (j=0; j<10; j++) {
if (i > 3 && j > 3) {
break mainLoop;
}
}
}
By giving the first loop a label of mainLoop, it can be broken out of easily within the nested loop using break mainLoop; This creates cleaner code and removes the necessity for the extra variable.
Chaoswarp
06-30-2006, 04:37 PM
Yo senocular,
thanks for the tips, really helpful in getting into this stuff.
Couple questions,
First with the scopeing...
traceThis.call(new Sprite()); // "Class Instance"
if this call keeps the class scope, why bother passing in another object? I kinda though the point of .call and .apply where to change scopes in functions? So i guess i am just wondering, why would u ever need to pass something into .call? wouldnt they all just be
func.call(null, a,b,c);
Secondly the casting stuff
var m:int = 8
var t:String = m as String
var o:String = String(m)
trace(t) //null?
trace(o) //8
how come i am getting null, maybe i am just not understanding this, but shouldnt those do the same thing?
Thanks again!
senocular
06-30-2006, 06:09 PM
if this call keeps the class scope, why bother passing in another object? I kinda though the point of .call and .apply where to change scopes in functions? So i guess i am just wondering, why would u ever need to pass something into .call?
In the case of class methods, call is pretty useless. Apply is still helpful because it can let you use an array as arguments, but neither will let you change the scope of a function if it is defined as a method of a class. Class methods are bound to the scope of the class and cannot change so passing any scope object is redundant. Call and apply, however, will work on anonymous functions defined, for example, in a class method or the constructor.
Secondly the casting stuff... how come i am getting null, maybe i am just not understanding this, but shouldnt those do the same thing?
Casting with the as operator does not convert a datatype, it only changes Flash's understanding of what that variable's type is and only if compatible. By compatible I mean the original variable's class or any type within that class's hierarchy. So if an object is a Sprite and it was returned from a function as a Display Object (such as getChildAt would do), then you would most likely want to use as to reassociate it's type to be a Sprite. as would also work to change the value's type to any other object within the Sprite's heirarchy:
Sprite -DisplayObjectContainer -InteractiveObject -DisplayObject -EventDispatcher -Object
though you'd generally want to stick with the constructor class since it is more appropriate to your object.
Conversion functions are used to convert a value to another value of a different type. When converting a number to a string, you would use a conversion function (String()) because Numbers do not inherit from String. Because of that, as would fail.
Number -Object
Conversion functions are typically the class name called as a function, though simple casting will be used if there is no actual casting function associated with the class (with, for example, your custom classes; String, however, is a unique conversion function).
Chaoswarp
06-30-2006, 06:24 PM
thanks that makes more sense. :)
NEW Question, and maybe I am just all together spacing out on this one.. but uhm where are the Tween Classes?
I attempted to do import mx.effects.Tween... but that doesnt work, nor do i think it should. I hunted through all the class files, and those still all look flash 8.
Can ya gimme a hint as to how to get going tweening things with AS3? I know i could make my own timers and do it myself, but I am looking to find out what happened to the Tween Class.
Also where does flash store the class files i am importing. for example where is flash.display.MovieClip. Does that class file exist on my computer? or is it in the flash player? can i use mx classes? if so where are those located for AS 3?
Any help would be appriciated, i am pretty much looking for a simple example like.. there is a circle movieclip made with a class, function called bounceIt. and in the bounceIt function it creates a new tween and bounces the ball up and down.
Sorry if these are all retarded, just trying to get a head start :)
senocular
07-01-2006, 01:30 AM
All classes that you import from the flash packages (packages that begin with flash.) are internal to the Flash player. These are the fundamentals by which everything you program is based on. Other classes are external; these include the classes in the mx packages. You can find all of the source files for the mx classes in Flash's installation directory (or Flex's frameworks directory). The tweening classes are a part of these classes and they still exist for ActionScript 9.
mx.effects.Tween;
senocular
07-01-2006, 02:10 AM
One thing about previous versions of ActionScript was that you could never tell when the user no longer had his or her mouse over the Flash movie. This made it hard for people to know whether or not the user is still interacting with their movie or if they've given up and moved on to something more interesting. This was especially a problem for custom cursors where, if the user moved the cursor off the Flash movie, the custom cursor would still remain in the Flash movie not moving while the real cursor could be seen moving around every where else.
ActionScript 3 now allows you to detect when the mouse has left the flash movie using the stage's mouseLeave event. This event happens whenever the mouse exits the Flash movie. There is no mouseEnter event, but you can use mouseMove for that since mouseMove only occurs in Flash (for the stage, or really any, object) when the mouse is within the bounds of the movie.
Here's a simple example that uses a square as a custom cursor:
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Mouse;
public class Test extends Sprite {
private var cursor:Sprite = new Sprite();
public function Test() {
cursor.graphics.beginFill(0xFF);
cursor.graphics.drawRect(0, 0, 25, 25);
addChild(cursor);
stage.addEventListener(Event.MOUSE_LEAVE, cursorHide);
stage.addEventListener(MouseEvent.MOUSE_MOVE, cursorFollow);
Mouse.hide();
}
public function cursorHide(evt:Event):void {
cursor.visible = false;
}
public function cursorFollow(evt:MouseEvent):void {
if (!cursor.visible) cursor.visible = true;
cursor.x = stage.mouseX;
cursor.y = stage.mouseY;
evt.updateAfterEvent();
}
}
}
As your mouse leaves the movie, the cursor sprite is hidden. When the mouse is brought back in the movie, the mouseMove event fires and the cursor is made visible again.
Chaoswarp
07-01-2006, 01:22 PM
Hmmmm well if the tween classes still exist, and should work the same. what am I doin wrong?
I got a movieclip mc on the timeline, ofcourse.
import mx.effects.Tween
var t = new Tween(mc, "_rotation", Elastic.easeOut, 0,360, 3, true)
this gives me a compiler error
ReferenceError: Error #1065: Variable Tween is not defined.
at Timeline0_63425fcc21fc6e4194dfe8880df15cd/::frame1()
So what is the proper way to get access to the Tween class?
senocular
07-01-2006, 01:28 PM
for 1, _rotation is now rotation, but more importantly it looks like the AS3 preview didn't come with updated AS3 mx classes. You'll have to live without them (or use Flex or the Flex SDK)
You also haven't included the package with `Elastic` in it.
I think that package is mx.transitions.easing.*
Not that it matters if the package wasn't included for AS3.
TheCanadian
07-01-2006, 05:34 PM
Actually it's in mx.effects.easing
Chaoswarp
07-01-2006, 06:23 PM
hehe yah knew about the other classes, figured it was pointless if i couldnt find this one. :)
thanks though, saves me some headache. Also is it just me, or does the code Check in flash IDE not work on AS 3 classes?
senocular - Can I get the updated Class files from the SDK or some from flex somewhere? like just copy them over my other ones? Or do i need to develop in flex until they release a new flash 9, if i wanna use those features?
thanks
senocular
07-01-2006, 06:40 PM
You should be able to use the classes from the Flex SDK. Just download them somewhere on your computer and specify the location of the folder with the mx directory in your Flash preferences class path.
senocular
07-02-2006, 10:54 AM
ActionScript 3 now supports a new class called SimpleButton (flash.display.SimpleButton (http://livedocs.macromedia.com/flex/2/langref/flash/display/SimpleButton.html)). This class lets you create button symbols in ActionScript - something previously not possible older versions of ActionScript.
var myButton:SimpleButton = new SimpleButton();
The SimpleButton class contains 4 properties that relate to the various states of a button; upState, overState, downState, and hitAreaState. Create display objects for these states and assign them to those properties to create a fully functional button symbol using ActionScript 3.
myButton.upState = mySprite1;
myButton.overState = mySprite2;
myButton.downState = mySprite3;
myButton.hitAreaState = mySprite4;
senocular
07-02-2006, 01:40 PM
You should be able to use the classes from the Flex SDK. Just download them somewhere on your computer and specify the location of the folder with the mx directory in your Flash preferences class path.
It looks like there's a lot of underlying complications in the mx framework provided with Flex that prevent this from being possible. So it looks like to use the Tween class in AS3, you'll have to rewrite it yourself ;)
Enemу
07-03-2006, 02:43 PM
Here's a simple example that uses a square as a custom cursor:
...
public function cursorFollow(evt:MouseEvent):void {
if (!cursor.visible) cursor.visible = true;
cursor.x = stage.mouseX;
cursor.y = stage.mouseY;
evt.updateAfterEvent();
}
Pls, comment on evt.updateAfterEvent(); , I know what updateAfterEvent() function does, but placing evt object before it confuses me.
It instructs player to refresh stage after event completes, right?
Why don't just write
updateAfterEvent(); ?
I'll be thankfull if someone will point me on docs describing updateAfterEvent();
Krilnon
07-03-2006, 03:06 PM
updateAfterEvent() is a method of the MouseEvent class, not a global function, so you need to call it from an instance of the MouseEvent class, in this case, 'evt'.
It is also a method of the KeyboardEvent and TimerEvent classes.
Here is the link to the documentation: http://livedocs.macromedia.com/labs/1/flex20beta3/langref/flash/events/MouseEvent.html#updateAfterEvent()
senocular
07-04-2006, 12:00 PM
When defining arrays in ActionScript 3 using the shorthand array access operator (brackets), you can now have a trailing comma following the last element without causing an error (like in PHP). This makes working with multi-line array definitions a little less error-prone when rearranging elements. Ex:
var myList:Array = [
"The",
"quick",
"brown",
"fox",
];
In ActionScript 1 and 2, the comma after "fox" would create an error. This is not the case in ActionScript 3.
Note: this does not work with Array() or new Array(), only [].
senocular
07-04-2006, 12:14 PM
Packages in ActionScript 3 are defined a little differently than they are in ActionScript 2. In ActionScript 3, the package path is no longer part of the class definition. Instead, it is part of a new block which contains your class, the package block defined with the package keyword. That gives you the following basic structure for AS3 files:
package my.package.path {
class MyClass {
}
}
In AS2, it would look like the following:
// ActionScript 2:
class my.package.path.MyClass {
}
In fact, in AS3, all class files require a package block, even if they are not in a package.
package {
class NotInAPackageClass {
}
}
Each package block can define a class or a function that is associated with the file. The class or function within the block should be defined with the same name as the file (minus the .as extension).
package com.kirupa.utils {
function StripString(str:String):void {
// ...
}
}
The above would be saved as StripString.as in a com/kirupa/utils folder.
senocular
07-04-2006, 12:59 PM
I'm going to skip ahead a little because the next two topics are related to the one I just posted
senocular
07-04-2006, 01:01 PM
Class definitions typically belong in their own .as file for either ActionScript 2 or 3. ActionScript 3, however, allows you to include additional helper classes within a single .as file in addition to your primary class.
Additional classes defined in an .as file are defined after a package block and are visible only to the primary class (or function) in the package block or other helper classes in the same file.
package {
class MyClass {
function MyClass() {
var helper:MyHelper = new MyHelper();
}
}
}
class MyHelper {
function MyHelper() {
var helper:HelpersHelper = new HelpersHelper();
}
}
class HelpersHelper {
function HelpersHelper () {
}
}
Remember that only one class can be defined in a package block. Additional helper classes defined in the same file are not part of the package and can be used only with the packaged class in the same file.
senocular
07-04-2006, 01:29 PM
ActionScript 3 introduces 2 new access attributes for classes and members and refines the private attribute of ActionScript 2. In ActionScript 3 you have the following attributes for controlling access:
public
protected
private
internal (default)
public: The public attribute is the same as it was in ActionScript 2. Anything defined as public can be accessed anywhere by anything.
Constructors are always public.
Application classes need to be public.
protected: The protected attribute is a new attribute for ActionScript. It sets variables hidden from all access except from subclasses accessing the variables (inherited) from their own instance. Attempting to access a protected variable from another class instance in any circumstance will result in an error.
Classes and constructors cannot be defined as protected.
private: AS2 had the private attribute but it worked more like protected as subclasses had full access to private members. Now, with AS3, private is completely private and is only accessible from within the class in which it is defined. To all other classes, even subclasses, a private member doesn't even exist. This means that subclasses can even define new members of the same name and not have a conflict since the private member of the superclass is completely hidden. Private members are accessible directly off of class instances only when done so within the class definition.
Classes and constructors cannot be defined as private.
internal: Internal access is similar to public access but is restricted to package definitions. Classes in the same package have access to all internal members of any other class in that package. Classes in other packages do not have access.
Internal is the default for every class and class member except constructors which are always public.
Access control in helper classes are a little different. Since helper classes don't technically belong in packages, internal access for them is restricted to the classes in the current file. Helper classes themselves are inherently internal in this respect (and do not need to be explicitly provided any form of access attribute). Other access attributes within helper classes behave as expected. Note: your primary class cannot extend a helper class. Only helper classes can extend other helper classes and they need to be in the same file.
Something to keep in mind that access control for AS3 is also enforced not only during compile time, but also runtime. Hacks used in AS2 to get by accessing hidden methods will no longer work in AS3.
Example 1
package {
import flash.display.Sprite;
// Application class needs to be public (internal by default)
public class AccessControl extends Sprite {
// constructors are always public
function AccessControl() {
// only classes in this file
// can access helper classes
var helper:Helper = new Helper();
trace(helper.pubNum); // OK
// trace(helper.protNum); // Error - cannot access protected
// trace(helper.privNum); // Error - cannot access private
trace(helper.interNum); // OK
}
}
}
// Helper class is implicitly internal
class Helper {
// public access granted anywhere
// variables are usually protected or
// private with get/set used for public access
public var pubNum:Number = 1;
// protected access granted only for
// subclasses in that class
protected var protNum:Number = 2;
// private access granted only in this class
private var privNum:Number = 3;
// internal access granted only in the same
// package, but for helper classes, it means
// only in the same file
internal var interNum:Number = 4;
// constructors are always public
function Helper() {
}
}
// SubHelper class is implicitly internal
// can extend other helper classes
class SubHelper extends Helper {
// constructors are always public
function SubHelper() {
trace(pubNum); // OK
trace(protNum); // OK - inherited
// trace(privNum); // Error - cannot access private
trace(interNum); // OK
}
}
Example 2
package {
import flash.display.Sprite;
import containers.*;
// Application class needs to be public (internal by default)
public class AccessControl extends Sprite {
// constructors are always public
function AccessControl() {
// can access classes in other packages
// only if public
var bowl:Bowl = new Bowl(); // OK
// var basket:Basket = new Basket(); // Error - cannot access internal
trace(bowl.pubNum); // OK
// trace(bowl.protNum); // Error - cannot access protected
// trace(bowl.privNum); // Error - cannot access private
// trace(bowl.interNum); // Error - cannot access internal
}
}
}package containers {
// public class accessible anywhere
public class Bowl {
// public access granted anywhere
public var pubNum:Number = 1;
// protected access granted only for
// subclasses in that class
protected var protNum:Number = 2;
// private access granted only in this class
private var privNum:Number = 3;
// internal access granted only in the same package
internal var interNum:Number = 4;
// constructors are always public
function Bowl() {
// can access inteneral classes if in same package
var basket:Basket = new Basket();
trace(basket.pubNum); // OK
// trace(basket.protNum); // Error - cannot access protected
// trace(basket.privNum); // Error - cannot access private
trace(basket.interNum); // OK - same package
// clone using public method
var basketCopy:Basket = basket.clone();
}
}
}package containers {
// interal only accessible
// from other classes in package
internal class Basket {
// public access granted anywhere
public var pubNum:Number = 1;
// protected access granted only for
// subclasses in that class
protected var protNum:Number = 2;
// private access granted only in this class
private var privNum:Number = 3;
// internal access granted only in the same package
internal var interNum:Number = 4;
// constructors are always public
function Basket() {
}
// accessible anywhere as long as
// referencing a Basket instance
public function clone():Basket {
var basket:Basket = new Basket();
basket.pubNum = pubNum; // OK
basket.protNum = protNum; // OK - same class
basket.privNum = privNum; // OK - same class
basket.interNum = interNum; // OK
return basket;
}
}
}
devonair
07-06-2006, 04:35 AM
You should be able to use the classes from the Flex SDK. Just download them somewhere on your computer and specify the location of the folder with the mx directory in your Flash preferences class path.
Just gave that a go... I had to comment out the includes and delete all references to the mx_internal namespace (Senocular probably knows a more elegant method of "fixing" these things, I'm more a slash and burn kinda guy) and came up with this:
http://www.onebyonedesign.com/flash/f9/tween/ (click on the circle)
the script:
package com.onebyonedesign.tests {
import mx.effects.*;
import flash.display.*;
import flash.events.*;
import mx.effects.easing.*;
public class TweenTest extends Sprite {
private var _circle:Sprite;
function TweenTest() {
stage.frameRate = 31;
init();
}
private function init():void {
_circle = makeCircle();
_circle.addEventListener(MouseEvent.MOUSE_DOWN, tweenMe);
}
private function makeCircle():Sprite {
var s:Sprite = new Sprite();
s.graphics.beginFill(0x660000);
s.graphics.drawCircle(20, 20, 20);
addChild(s);
return s;
}
private function updateTween(vals:Array):void {
_circle.x = vals[0];
_circle.y = vals[1];
}
private function endTween(vals:Array):void {
trace ("ending coordinates: " + vals);
}
private function tweenMe(e:Event):void {
var myTween:Tween = new Tween(_circle, [_circle.x, _circle.y], [275, 200], 1000, 31);
myTween.easingFunction = Elastic.easeOut;
myTween.setTweenHandlers(updateTween, endTween);
}
}
}
the cool thing is that we can now add arrays of properties instead of doing one at a time.. Disco...
EDIT:
Thank you for these tips, Senocular.. Great thread and some great info...
Increu
07-06-2006, 08:26 AM
I dontknow whats hapenning, i am trying this code
import flash.utils.Dictionary;
var a:Object = new Object();
var b:Object = new Object();
var dict: Dictionary = new Dictionary();
dict[a] = 1; // dict[a] = 1;
dict[b] = 2; // dict[b] = 2;
for (var prop:String in dict) {
trace(prop); // traces: [object Object], [object Object]
trace(dict[prop]); // traces: 1, 2
}
and its not tracing 1,2, just undefined undefined
why why why???????
gpacioli
07-06-2006, 09:35 AM
I continue to hear and read about Flex --- someone in a Davie, Florida user group said, "Flex is Adobe's Number one priority." Is this the place to ask,
"What is Flex --- and what good does it do? Does it compete with Flash? Do I start to learn Flex when I'm just learning Flash. Or what the ... ?
senocular
07-06-2006, 10:29 AM
I dontknow whats hapenning, i am trying this code
import flash.utils.Dictionary;
var a:Object = new Object();
var b:Object = new Object();
var dict: Dictionary = new Dictionary();
dict[a] = 1; // dict[a] = 1;
dict[b] = 2; // dict[b] = 2;
for (var prop:String in dict) {
trace(prop); // traces: [object Object], [object Object]
trace(dict[prop]); // traces: 1, 2
}
and its not tracing 1,2, just undefined undefined
why why why???????
woops, that would be my fault - typo (actually force of habit) - but good that you pointed that out!
Why you are getting undefined in that trace is because I used String as the data type for the prop variable. Because of this, when iterating through the dict object, the values of prop in that loop are converted to their String equivalent instead of being the object themselves - exactly what you would use the dict object to avoid.
To fix this, you just have to make sure the prop variable isnt cast as a String. Because you actually don't know what prop could be, it should be cast as *. So the loop should look like:
for (var prop:* in dict) {
trace(prop); // traces: [object Object], [object Object]
trace(dict[prop]); // traces: 1, 2
}
So now, prop remains whatever type it actually exists within the dict object (Object in this case) and the second trace resolves correctly as dict[a] and dict[b] instead of dict["[object Object]"]
;)
senocular
07-06-2006, 10:32 AM
Just gave that a go... I had to comment out the includes and delete all references to the mx_internal namespace (Senocular probably knows a more elegant method of "fixing" these things, I'm more a slash and burn kinda guy) and came up with this:
http://www.onebyonedesign.com/flash/f9/tween/ (click on the circle)
very cool, devonair, thanks!
senocular
07-06-2006, 10:46 AM
I continue to hear and read about Flex --- someone in a Davie, Florida user group said, "Flex is Adobe's Number one priority." Is this the place to ask,
"What is Flex --- and what good does it do? Does it compete with Flash? Do I start to learn Flex when I'm just learning Flash. Or what the ... ?
Well, I wouldn't be so bold as to say Flex is Adobe's Number one priority. But, the short answer is, Flex is a programmer-centric develop environment and server for the creation and deployment of Flash-based rich internet applications (RIAs). It has a strong focus on UI components and web services for the exchange and presentation of data.
Does it compete with Flash? No, not really. Though Flex Builder is an IDE for creating Flash applications, it doesn't have any of the drawing tools Flash has for content creation, nor does it have any timeline necessary for animations. Flex Builder is more of a workshop to bring existing content together to quickly and easily create moderately sized or large, screen or form based RIAs. You can kind of think of Flex as a programmers Flash where Flash is more for designers and animators (though, admittedly, Flash suffers a bit in terms of animation).
Flex presentation server is a different beast altogether and is more about server-side deployment (even further from Flash then Builder).
Also see:
http://www.gskinner.com/blog/archives/2006/07/flex_2_from_a_f.html
Skinner's perspective on Flex (with a nice little analogy for Flex and Flash)
senocular
07-06-2006, 02:42 PM
Unfortunately ActionScript 3 does not support abstract classes (classes that cannot be instantiated only extended). So you cannot create your own abstract classes in Flash. However, be aware that some of the internal classes in ActionScript are internally abstract. These classes include:
DisplayObject (http://livedocs.macromedia.com/flex/2/langref/flash/display/DisplayObject.html)
InteractiveObject (http://livedocs.macromedia.com/flex/2/langref/flash/display/InteractiveObject.html)
DisplayObjectContainer (http://livedocs.macromedia.com/flex/2/langref/flash/display/DisplayObjectContainer.html)
Graphics (http://livedocs.macromedia.com/flex/2/langref/flash/display/Graphics.html)
As abstract classes, you cannot create instances of them directly using the new keyword.
var myObj:InteractiveObject = new InteractiveObject(); // ERROR
However, in addition to that, in ActionScript, it also means that you cannot directly subclass these classes and create instances of those subclasses
package {
import flash.display.DisplayObject;
public class MyDisplay extends DisplayObject{
public function MyDisplay (){
// ERROR
}
}
}
This has to do with the internal nature and how they are defined for the Player. If you attempt to subclass one of these classes and instantiate that subclass, you will get the same Argument Error that you would get if you tried to instantiate one of those classes directly.
Instead, what you would need to do is extend an internal class that already subclasses these classes. For example, if you wanted to extend DisplayObject, you could instead extend Shape, a light, internal class that is a subclass of DisplayObject.
Increu
07-07-2006, 12:22 AM
Why you are getting undefined in that trace is because I used String as the data type for the prop variable. Because of this, when iterating through the dict object, the values of prop in that loop are converted to their String equivalent instead of being the object themselves - exactly what you would use the dict object to avoid.
To fix this, you just have to make sure the prop variable isnt cast as a String. Because you actually don't know what prop could be, it should be cast as *. So the loop should look like:
Ok..now i see it!!Thanks Sen!!
Just one more thing...i dont know if i understand it rigth, it is correct to say that the dictionary is for add properties to things that already exists
or
the dictionary is in fact, creating a new object inside the dictionary instance and the name of this object is a string and this string is the same name of any object i want...
Now i am confused...
senocular
07-07-2006, 02:14 AM
all Dictionary objects are, are Object objects that dont convert their keys to strings.
senocular
07-07-2006, 01:01 PM
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:
package {
import flash.display.*;
class MySprite extends Sprite {
private var children:Array = new Array();
public function MySprite() {
}
public override function addChild(child:DisplayObject):DisplayObject {
children.push(child);
super.addChild(child);
return child;
}
}
}
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:
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
Also be aware that override is not needed for methods inherited directly from the Object class. These include:
hasOwnProperty
isPrototypeOf
propertyIsEnumerable
setPropertyIsEnumerable
toString
valueOf
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.
senocular
07-08-2006, 11:01 PM
The prototype object in ActionScript is an object that exists among classes whose values are shared among all instances of the class to which it belongs. In ActionScript 1 and 2, it was used to control class inheritance. When a subclass instance references a variable, it first checks for that variable in the instance, followed by the class's prototype, followed by the superclass's prototype and so on through the prototype (inheritance) chain until there are no more classes.
In ActionScript 3, inheritance is primarily managed through Class inheritance and does not depend on the prototype object. However, the prototype object still exists and still provides much of the same functionality it did in AS1/AS2.
Each class and (non-method) function created in AS3 has a prototype object associated with it. For classes, prototype is read-only, meaning you cannot redefine it with a new value. However, it doesn't mean you cannot define new values within it (otherwise it would be pointless ;) ). Function prototypes are not read only. This allows you to create dynamic classes using the old style of class definitions through functions and set up inheritance through redefining the prototype.
Example:
package {
import flash.display.Sprite;
public dynamic class MyClass extends Sprite {
public function MyClass(){
// prototype = new Object(); // ERROR, cannot change prototype of class
prototype.newValue = 1; // OK, adding (or removing) prototyped values
trace(this.newValue); // 1
trace(prototype.toString); // function Function() {}
trace(prototype.addChild); // undefined
trace(addChild); // function Function() {}
// dynamic ("old style") class definition
var TempClass:Function = function():void {
trace("Create TempClass");
}
TempClass.prototype = prototype; // OK, can set up inheritance
var tempObject:* = new TempClass(); // "Create TempClass"
trace(tempObject.newValue); // 1
}
}
}
Note that you should always prefix dynamic variable references with the this keyword. Also note that the Object class methods are dynamic and are defined in the prototype (which is why they are not overridden with the override keyword). You may also notice that the tempObject is typed as * instead of TempClass. This is because TempClass is only recognized as being a Function in AS3, not an actual class though it can still be used as one. Though a Class type exists, dynamic classes created like TempClass will always be recognized as Functions so creating instances with them always generates instances typed as a generic object.
senocular
07-11-2006, 07:04 PM
ActionScript 3 now supports regular expressions! The implementation is much like the one used in JavaScript. You can create new regexp patterns with the RegExp (http://livedocs.macromedia.com/flex/2/langref/RegExp.html)class constructor (top level) and a string or using the literal text format (defined like a string only replacing quotes with a forward slash (/). Ex:
var reCon:RegExp = new RegExp("\\w+", "i");
var reLit:RegExp = /\w+/i;
RegExp methods include:
RegExp.exec()
RegExp.test()
String methods that work with regular expressions include:
String.match()
String.replace()
String.search()
senocular
07-11-2006, 07:36 PM
Because of how the display list works with ActionScript 3, some methods of depth sorting will no longer work. One in particular is sorting objects on the screen based on their y location. In ActionScript 1 and 2, you could simply tell the clip to swapDepths at its _y location and be done with it. With AS3, this is no longer possible since no gaps can exist within the depths display list ("array").
An approach to obtaining the same functionality in AS3 is possible through an sorted array. Store the objects you want to arrange in an array. Then sort that array based on the y properties of the display objects within. All you have to do after that is place them in the display list in the order sorted. Ex:
var sortedItems:Array = new Array(mc1, mc2, mc3);
function arrange():void {
sortedItems.sortOn("y", Array.NUMERIC);
var i:int = sortedItems.length;
while(i--){
if (getChildIndex(sortedItems[i]) != i) {
setChildIndex(sortedItems[i], i);
}
}
}
Here the sortedItems array stores the display objects being sorted (mc1 - mc3). In the arrange function, that array is sorted based on their y properties and then added to the display list at their locations within the array (if not already there).
Though this is not quite as easy as swaping to the depth of the _y property, it still proves a fairly efficient means of sorting objects on the screen based on their y location.
senocular
07-12-2006, 01:39 AM
Using the new ByteArray (flash.utils.ByteArray (http://livedocs.macromedia.com/flex/2/langref/flash/utils/ByteArray.html)) class in ActionScript 3, you can now easily create deep object copies. By deep, I mean being able to create copies not of just a single object and all its references, but also all the objects it references. This means if you use this method to copy an array which references an object, that object will also be copied as part of the copy procedure. Such a copy (clone) method would look like the following:
function clone(source:Object):* {
var copier:ByteArray = new ByteArray();
copier.writeObject(source);
copier.position = 0;
return(copier.readObject());
}
Note: you may need to import flash.utils.ByteArray;
To use this function simply say:
newObjectCopy = clone(originalObject);
Though this will make a deep copy of your objects, be aware that it does not retain class association. So, if you try to copy a MyClass instance, the copy will no longer be recognized as being of MyClass. This method is best used with generic objects.
senocular
07-12-2006, 11:38 AM
In ActionScript 1, you could have static properties of a class with the same name as instance properties. ActionScript 2 then came along and added a restriction preventing you from being able to do that. Now, with ActionScript 3, it is now again possible to have static properties with the same name as instance properties.
package {
import flash.display.Sprite;
public class MyApp extends Sprite {
private var variable:String;
private static var variable:String;
public function MyApp() {
this.variable = "foo";
MyApp.variable = "bar";
trace(this.variable); // "foo"
trace(MyApp.variable); // "bar"
trace(variable); // "foo"
}
}
}
senocular
07-14-2006, 01:05 AM
ActionScript 3 uses the EventDispatcher (flash.events.EventDispatcher (http://livedocs.macromedia.com/flex/2/langref/flash/events/EventDispatcher.html)) class for all event handling. This class was available in ActionScript 2, but it existed as an external class in the mx framework. Now, it is built into the player (and in being so, improves performance).
Whenever you want to create an event handler to be called during a certain event, whether it be every frame (enterFrame event), or at the press of a button (mouseDown event), in AS 3, you will need to use EventDispatcher. This means there are no more onEnterFrame of onPress functions you can define that will automatically handle these events, nor are there any simple addListener methods for generalized event listening. EventDispatcher and addEventListener (and related methods) does it all.
Methods
addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
dispatchEvent(event:Event):Boolean
hasEventListener(type:String):Boolean
removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
willTrigger(type:String):Boolean
Note that addEventListener only takes functions as listeners, not objects. Also remember that class methods are bound to their instances so when used as listeners, 'this' in the event call still references the orginal class instance no matter what object dispatched the event.
Basic Example:
package {
import flash.display.Sprite;
import flash.events.Event;
public class MyDispatcher extends Sprite {
public function MyDispatcher() {
addEventListener("customEvent", handleEvent);
dispatchEvent(new Event("customEvent"));
}
private function handleEvent(event:Event):void {
trace(event.type); // "customEvent"
}
}
}
By extending the EventDispatcher class or any class that inherits from it like Sprite (all DisplayObjects are inherently EventDispatchers), your class gains access to the EventDispatcher methods. Then, other instances (or the class instance itself) can add methods to instances of that class using addEventListener and in turn they can call those events through dispatchEvent.
If there is some reason your class cannot inherit from the EventDispatcher class (for example, if its already inheriting from another class which does not inherit from EventDispatcher), then you can use the EventDispatcher constructor to intialize your class instance with the methods of EventDispatcher via aggregation (composition). Just make sure you implement the IEventDispatcher interface (flash.events.IEventDispatcher). Ex:
package {
import flash.display.Sprite;
import flash.events.Event;
public class MyDispatcher extends Sprite {
public function MyDispatcher() {
var dispatcher:CustomDispatcher = new CustomDispatcher();
dispatcher.addEventListener("customEvent", handleEvent);
dispatcher.dispatchEvent(new Event("customEvent"));
}
private function handleEvent(event:Event):void {
trace(event.type); // "customEvent"
}
}
}
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
class CustomDispatcher implements IEventDispatcher {
private var eventDispatcher:EventDispatcher;
public function CustomDispatcher() {
eventDispatcher = new EventDispatcher(this);
}
public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void {
eventDispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference);
}
public function dispatchEvent(event:Event):Boolean {
return eventDispatcher.dispatchEvent(event);
}
public function hasEventListener(type:String):Boolean {
return eventDispatcher.hasEventListener(type);
}
public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void {
eventDispatcher.removeEventListener(type, listener, useCapture);
}
public function willTrigger(type:String):Boolean {
return eventDispatcher.willTrigger(type);
}
}
The CustomDispatcher helper class above doesn't inherit from EventDispatcher but uses aggregation to obtain EventDispatcher functionality through an instance of EventDispatcher initialized in the constructor.
senocular
07-14-2006, 03:00 AM
Event objects used with EventDispatcher in ActionScript 3 are a little less generic than those used with ActionScript 2. In AS 3, each event object has its own class. The most common event classes are Event (flash.events.Event (http://livedocs.macromedia.com/flex/2/langref/flash/events/Event.html)) for general events and MouseEvent (flash.events.MouseEvent (http://livedocs.macromedia.com/flex/2/langref/flash/events/MouseEvent.html)) for events associated with the mouse. Other event classes can be found in the flash.events package, all of which inherit from Event.
When using EventDispatcher.dispatchEvent(), you pass in an Event instance that is specific to the event being dispatched. The type of event dispatched is defined within the Event instance used. For example, dispatching an "enterFrame" event would mean using dispatchEvent with an Event instance instantiated with the type "enterFrame".
dispatchEvent(new Event("enterFrame"));
When an event handler is executed as a result of this event, that event object is passed into the function as a single argument. Properties from that event can then be extracted to learn more about the event that occured. For example, the type property from the Event class tells which event was dispatched.
addEventListener("enterFrame", eventHandler);
dispatchEvent(new Event("enterFrame"));
...
private function eventHandler(event:Event):void {
trace(event.type); // "enterFrame"
}
Though event types are strings, all common Flash events are available in Flash through static constants of the Event classes. The "enterFrame" event type, for example, is accessible using Event.ENTER_FRAME. Mouse events are within the MouseEvent class. Click events, for example, are MouseEvent.CLICK. These constants are prefered over their string representations.
addEventListener(Event.ENTER_FRAME, eventHandler);
dispatchEvent(new Event(Event.ENTER_FRAME));
When making your custom Events, you can use the Event object with a custom type or alternatively, extend the Event class creating a new kind of Event instance to be used with your events.
senocular
07-14-2006, 05:28 PM
In ActionScript 3, you can define XML variables using inline XML in your script. You don't even need to enclose it in Strings like you did in previous versions of ActionScript. The ActionScript 3 compiler will automatically parse the XML in the code and recognize when it stops and when normal AS code starts.
var myXml:XML =
<body>
<!-- comment -->
text1
<a>
<b>text2</b>
</a>
</body>;
gerardo
07-14-2006, 08:45 PM
Hey senocular, jus wondering if you can post something about the new URLLoader and URLRequest use with PHP. Thanks in advance.
senocular
07-14-2006, 08:51 PM
Hey senocular, jus wondering if you can post something about the new URLLoader and URLRequest use with PHP. Thanks in advance.
If you have a specific question, post a new thread about it in the forum
senocular
07-17-2006, 10:53 AM
ActionScript 3 lets you easily obtain any instances class name using a new function called getQualifiedClassName (flash.utils.getQualifiedClassName (http://livedocs.macromedia.com/flex/2/langref/flash/utils/package.html#getQualifiedClassName())).
var sprite:Sprite = new Sprite();
trace(getQualifiedClassName(sprite)); // "flash.display::Sprite"
You can also use the getQualifiedSuperclassName (flash.utils.getQualifiedSuperclassName (http://livedocs.macromedia.com/flex/2/langref/flash/utils/package.html#getQualifiedSuperclassName())) function to find its superclass
trace(getQualifiedSuperclassName(sprite)); // "flash.display::DisplayObjectContainer"
If you want to go backwards, and convert a string into an actual class reference, you can use getDefinitionByName (flash.utils.getDefinitionByName (http://livedocs.macromedia.com/flex/2/langref/flash/utils/package.html#getDefinitionByName())).
trace(getDefinitionByName("flash.display::Sprite")); // [class Sprite]
Also see describeType() (flash.utils.describeType (http://livedocs.macromedia.com/flex/2/langref/flash/utils/package.html#describeType())) in the following post...
devonair
07-17-2006, 01:03 PM
that's beautiful.. so much better than typeof.. Though I might also add (if I may), if you want some extremely (almost stupid amount of) detailed info about your class type, you can also use describeType()..
so
var sprite:Sprite = new Sprite();
var spriteDescription:XML = describeType(sprite);
trace (spriteDescription);
traces:
<type name="flash.display::Sprite" base="flash.display::DisplayObjectContainer" isDynamic="false" isFinal="false" isStatic="false">
<extendsClass type="flash.display::DisplayObjectContainer"/>
<extendsClass type="flash.display::InteractiveObject"/>
<extendsClass type="flash.display::DisplayObject"/>
<extendsClass type="flash.events::EventDispatcher"/>
<extendsClass type="Object"/>
<implementsInterface type="flash.events::IEventDispatcher"/>
<implementsInterface type="flash.display::IBitmapDrawable"/>
<accessor name="buttonMode" access="readwrite" type="Boolean" declaredBy="flash.display::Sprite"/>
<accessor name="soundTransform" access="readwrite" type="flash.media::SoundTransform" declaredBy="flash.display::Sprite"/>
<accessor name="useHandCursor" access="readwrite" type="Boolean" declaredBy="flash.display::Sprite"/>
<method name="stopDrag" declaredBy="flash.display::Sprite" returnType="void"/>
<accessor name="dropTarget" access="readonly" type="flash.display::DisplayObject" declaredBy="flash.display::Sprite"/>
<accessor name="graphics" access="readonly" type="flash.display::Graphics" declaredBy="flash.display::Sprite"/>
<accessor name="hitArea" access="readwrite" type="flash.display::Sprite" declaredBy="flash.display::Sprite"/>
<method name="startDrag" declaredBy="flash.display::Sprite" returnType="void">
<parameter index="1" type="Boolean" optional="true"/>
<parameter index="2" type="flash.geom::Rectangle" optional="true"/>
</method>
<method name="swapChildren" declaredBy="flash.display::DisplayObjectContainer" returnType="void">
<parameter index="1" type="flash.display::DisplayObject" optional="false"/>
<parameter index="2" type="flash.display::DisplayObject" optional="false"/>
</method>
<accessor name="tabChildren" access="readwrite" type="Boolean" declaredBy="flash.display::DisplayObjectContainer"/>
<method name="getObjectsUnderPoint" declaredBy="flash.display::DisplayObjectContainer" returnType="Array">
<parameter index="1" type="flash.geom::Point" optional="false"/>
</method>
<method name="getChildAt" declaredBy="flash.display::DisplayObjectContainer" returnType="flash.display::DisplayObject">
<parameter index="1" type="int" optional="false"/>
</method>
<method name="removeChildAt" declaredBy="flash.display::DisplayObjectContainer" returnType="flash.display::DisplayObject">
<parameter index="1" type="int" optional="false"/>
</method>
<method name="getChildIndex" declaredBy="flash.display::DisplayObjectContainer" returnType="int">
<parameter index="1" type="flash.display::DisplayObject" optional="false"/>
</method>
<method name="areInaccessibleObjectsUnderPoint" declaredBy="flash.display::DisplayObjectContainer" returnType="Boolean">
<parameter index="1" type="flash.geom::Point" optional="false"/>
</method>
<method name="contains" declaredBy="flash.display::DisplayObjectContainer" returnType="Boolean">
<parameter index="1" type="flash.display::DisplayObject" optional="false"/>
</method>
<accessor name="mouseChildren" access="readwrite" type="Boolean" declaredBy="flash.display::DisplayObjectContainer"/>
<method name="removeChild" declaredBy="flash.display::DisplayObjectContainer" returnType="flash.display::DisplayObject">
<parameter index="1" type="flash.display::DisplayObject" optional="false"/>
</method>
<method name="setChildIndex" declaredBy="flash.display::DisplayObjectContainer" returnType="void">
<parameter index="1" type="flash.display::DisplayObject" optional="false"/>
<parameter index="2" type="int" optional="false"/>
</method>
<method name="addChildAt" declaredBy="flash.display::DisplayObjectContainer" returnType="flash.display::DisplayObject">
<parameter index="1" type="flash.display::DisplayObject" optional="false"/>
<parameter index="2" type="int" optional="false"/>
</method>
<accessor name="numChildren" access="readonly" type="int" declaredBy="flash.display::DisplayObjectContainer"/>
<method name="addChild" declaredBy="flash.display::DisplayObjectContainer" returnType="flash.display::DisplayObject">
<parameter index="1" type="flash.display::DisplayObject" optional="false"/>
</method>
<method name="getChildByName" declaredBy="flash.display::DisplayObjectContainer" returnType="flash.display::DisplayObject">
<parameter index="1" type="String" optional="false"/>
</method>
<accessor name="textSnapshot" access="readonly" type="flash.text::TextSnapshot" declaredBy="flash.display::DisplayObjectContainer"/>
<method name="swapChildrenAt" declaredBy="flash.display::DisplayObjectContainer" returnType="void">
<parameter index="1" type="int" optional="false"/>
<parameter index="2" type="int" optional="false"/>
</method>
<accessor name="doubleClickEnabled" access="readwrite" type="Boolean" declaredBy="flash.display::InteractiveObject"/>
<accessor name="contextMenu" access="readwrite" type="flash.ui::ContextMenu" declaredBy="flash.display::InteractiveObject"/>
<accessor name="accessibilityImplementation" access="readwrite" type="flash.accessibility::AccessibilityImplementation" declaredBy="flash.display::InteractiveObject">
<metadata name="Inspectable">
<arg key="environment" value="none"/>
</metadata>
</accessor>
<accessor name="mouseEnabled" access="readwrite" type="Boolean" declaredBy="flash.display::InteractiveObject"/>
<accessor name="focusRect" access="readwrite" type="Object" declaredBy="flash.display::InteractiveObject"/>
<accessor name="tabIndex" access="readwrite" type="int" declaredBy="flash.display::InteractiveObject"/>
<accessor name="tabEnabled" access="readwrite" type="Boolean" declaredBy="flash.display::InteractiveObject"/>
<accessor name="alpha" access="readwrite" type="Number" declaredBy="flash.display::DisplayObject"/>
<accessor name="scale9Grid" access="readwrite" type="flash.geom::Rectangle" declaredBy="flash.display::DisplayObject"/>
<accessor name="name" access="readwrite" type="String" declaredBy="flash.display::DisplayObject"/>
<accessor name="filters" access="readwrite" type="Array" declaredBy="flash.display::DisplayObject"/>
<accessor name="y" access="readwrite" type="Number" declaredBy="flash.display::DisplayObject"/>
<accessor name="rotation" access="readwrite" type="Number" declaredBy="flash.display::DisplayObject"/>
<accessor name="scrollRect" access="readwrite" type="flash.geom::Rectangle" declaredBy="flash.display::DisplayObject"/>
<accessor name="x" access="readwrite" type="Number" declaredBy="flash.display::DisplayObject"/>
<accessor name="cacheAsBitmap" access="readwrite" type="Boolean" declaredBy="flash.display::DisplayObject"/>
<accessor name="accessibilityProperties" access="readwrite" type="flash.accessibility::AccessibilityProperties" declaredBy="flash.display::DisplayObject"/>
<method name="globalToLocal" declaredBy="flash.display::DisplayObject" returnType="flash.geom::Point">
<parameter index="1" type="flash.geom::Point" optional="false"/>
</method>
<method name="getBounds" declaredBy="flash.display::DisplayObject" returnType="flash.geom::Rectangle">
<parameter index="1" type="flash.display::DisplayObject" optional="false"/>
</method>
<accessor name="opaqueBackground" access="readwrite" type="Object" declaredBy="flash.display::DisplayObject"/>
<method name="hitTestPoint" declaredBy="flash.display::DisplayObject" returnType="Boolean">
<parameter index="1" type="Number" optional="false"/>
<parameter index="2" type="Number" optional="false"/>
<parameter index="3" type="Boolean" optional="true"/>
</method>
<accessor name="visible" access="readwrite" type="Boolean" declaredBy="flash.display::DisplayObject"/>
<accessor name="mouseX" access="readonly" type="Number" declaredBy="flash.display::DisplayObject"/>
<accessor name="mask" access="readwrite" type="flash.display::DisplayObject" declaredBy="flash.display::DisplayObject"/>
<method name="getRect" declaredBy="flash.display::DisplayObject" returnType="flash.geom::Rectangle">
<parameter index="1" type="flash.display::DisplayObject" optional="false"/>
</method>
<accessor name="scaleX" access="readwrite" type="Number" declaredBy="flash.display::DisplayObject"/>
<accessor name="scaleY" access="readwrite" type="Number" declaredBy="flash.display::DisplayObject"/>
<accessor name="root" access="readonly" type="flash.display::DisplayObject" declaredBy="flash.display::DisplayObject"/>
<accessor name="loaderInfo" access="readonly" type="flash.display::LoaderInfo" declaredBy="flash.display::DisplayObject"/>
<method name="hitTestObject" declaredBy="flash.display::DisplayObject" returnType="Boolean">
<parameter index="1" type="flash.display::DisplayObject" optional="false"/>
</method>
<accessor name="transform" access="readwrite" type="flash.geom::Transform" declaredBy="flash.display::DisplayObject"/>
<accessor name="width" access="readwrite" type="Number" declaredBy="flash.display::DisplayObject"/>
<accessor name="stage" access="readonly" type="flash.display::Stage" declaredBy="flash.display::DisplayObject"/>
<accessor name="parent" access="readonly" type="flash.display::DisplayObjectContainer" declaredBy="flash.display::DisplayObject"/>
<accessor name="height" access="readwrite" type="Number" declaredBy="flash.display::DisplayObject"/>
<method name="localToGlobal" declaredBy="flash.display::DisplayObject" returnType="flash.geom::Point">
<parameter index="1" type="flash.geom::Point" optional="false"/>
</method>
<accessor name="mouseY" access="readonly" type="Number" declaredBy="flash.display::DisplayObject"/>
<accessor name="blendMode" access="readwrite" type="String" declaredBy="flash.display::DisplayObject"/>
<method name="removeEventListener" declaredBy="flash.events::EventDispatcher" returnType="void">
<parameter index="1" type="String" optional="false"/>
<parameter index="2" type="Function" optional="false"/>
<parameter index="3" type="Boolean" optional="true"/>
</method>
<method name="addEventListener" declaredBy="flash.events::EventDispatcher" returnType="void">
<parameter index="1" type="String" optional="false"/>
<parameter index="2" type="Function" optional="false"/>
<parameter index="3" type="Boolean" optional="true"/>
<parameter index="4" type="int" optional="true"/>
<parameter index="5" type="Boolean" optional="true"/>
</method>
<method name="toString" declaredBy="flash.events::EventDispatcher" returnType="String"/>
<method name="dispatchEvent" declaredBy="flash.events::EventDispatcher" returnType="Boolean">
<parameter index="1" type="flash.events::Event" optional="false"/>
</method>
<method name="hasEventListener" declaredBy="flash.events::EventDispatcher" returnType="Boolean">
<parameter index="1" type="String" optional="false"/>
</method>
<method name="willTrigger" declaredBy="flash.events::EventDispatcher" returnType="Boolean">
<parameter index="1" type="String" optional="false"/>
</method>
</type>
I just love AS3... really, I do...
senocular
07-17-2006, 01:10 PM
I was going to save that as a tip for another day :bad: but thanks :trout:
McGuffin
07-17-2006, 01:35 PM
Sen, question about getDefinitionByName(). Does the class need to be hardcoded into the file before using the returned value for getDefinitionByName()? Example:
I have a pageType field in a MySQL database that tells the Flash site which page template to use for its pages. Homepage, Aboutpage, etc. I use:
var className:String = "pages."+_root.pageDatabase.getPageType(i);
var theStringClass:Function = mx.utils.ClassFinder.findClass(className);
_root["pageInstance"+i] = new theStringClass();
To create each page. The problem is, I need to hardcode an instance of each of these page classes into my site so that file will load and keep the class.
var homepagedisplay = new pages.Homepage();
delete homepagedisplay;
I'd like to skip that step, seeing as how I could have it completely dynamic if I didn't have to hardcode in anything.
senocular
07-17-2006, 02:04 PM
You should need to at least import the needed classes into your file if not native player classes. If you dont, Flash will not have them in the SWF to use. With AS3, instantiation shouldnt be required (and really, with AS2, it wasnt either as long as you used the class reference somewhere).
devonair
07-17-2006, 02:08 PM
I was going to save that as a tip for another day :bad: but thanks :trout:
whoops.. sorry - seemed to fit the topic...
senocular
07-17-2006, 02:09 PM
I almost added it as part of that one, but I was starting to get a little thin on topics, and since they were every day I'm going to try to stretch them out. Not a big deal ;)
senocular
07-18-2006, 12:15 AM
In ActionScript 2, the call to super() in the constructor of a class inheriting from another class had to be the first statement within the constructor. If you didn't add it explicitly yourself, it was added for you.
In ActionScript 3, super will still be added for you if you did not include it yourself, but now you are allowed to place it anywhere within your constructor, even after other statements; it no longer has to be the first statement in your constructor.
package {
public class SubClass extends SuperClass {
protected var value:int;
public function SubClass(value:int = 0) {
this.value = value;
super(20);