kirupaForum

kirupaForum (http://www.kirupa.com/forum/index.php)
-   Flash ActionScript (http://www.kirupa.com/forum/forumdisplay.php?f=9)
-   -   ActionScript 3.0 Tip of the Day (http://www.kirupa.com/forum/showthread.php?t=223798)

senocular 07-14-2006 01:28 PM

Writing Inline XML
 
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.

ActionScript Code:

var myXml:XML =
        <body>
            <!-- comment -->
            text1
            <a>
                <b>text2</b>
            </a>
        </body>;


gerardo 07-14-2006 04: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 04:51 PM

Quote:

Originally Posted by gerardo
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 06:53 AM

Determine Instance Class or Superclass
 
ActionScript 3 lets you easily obtain any instances class name using a new function called getQualifiedClassName (flash.utils.getQualifiedClassName).
ActionScript Code:

var sprite:Sprite = new Sprite();
trace(getQualifiedClassName(sprite)); // "flash.display::Sprite"
 


You can also use the getQualifiedSuperclassName (flash.utils.getQualifiedSuperclassName) function to find its superclass
ActionScript Code:

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).
ActionScript Code:

trace(getDefinitionByName("flash.display::Sprite")); // [class Sprite]
 



Also see describeType() (flash.utils.describeType) in the following post...

devonair 07-17-2006 09:03 AM

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
ActionScript Code:

var sprite:Sprite = new Sprite();
var spriteDescription:XML = describeType(sprite);
trace (spriteDescription);



traces:
Code:

<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 09:10 AM

I was going to save that as a tip for another day :bad: but thanks :trout:

McGuffin 07-17-2006 09:35 AM

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:

ActionScript Code:

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.

ActionScript Code:

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 10:04 AM

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 10:08 AM

Quote:

Originally Posted by senocular
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 10:09 AM

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-17-2006 08:15 PM

super() Placement (Now Anywhere)
 
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.

ActionScript Code:

package {
    public class SubClass extends SuperClass {
        protected var value:int;
        public function SubClass(value:int = 0) {
            this.value = value;
            super(20);
        }
    }
}


senocular 07-17-2006 08:20 PM

super() Placement (Now Anywhere)
 
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.

ActionScript Code:

package {
    public class SubClass extends SuperClass {
        protected var value:int;
        public function SubClass(value:int = 0) {
            this.value = value;
            super(20);
        }
    }
}


senocular 07-18-2006 08:45 AM

Just a little FYI - I changed the links in the index to reference the posts in the context of the thread. This makes it a little easier to go through and read related posts as well :)

Krilnon 07-18-2006 09:31 AM

If you extend a class, the constructor for the extended class won't run upon instantiation, but it can still be accessed with super, correct?

senocular 07-18-2006 09:44 AM

the super class constructor will still run, you can just decide when now (AS2 it was always before any other code).

Krilnon 07-18-2006 11:27 AM

You might want to edit the override post to mention that when you override methods that use the AS3 namespace, you need to include the namespace in your override definition.

The post mentions the need to match the method signature, but it probably took me half of an hour to figure out that I needed to include the namespace to avoid an error I was getting when overriding Array.push().

senocular 07-19-2006 03:04 PM

Determining Current Frame Label
 
MovieClip (flash.display.MovieClip) instances in ActionScript 3 have a couple of new properties called currentLabels and currentLabel. currentLabels is an array of FrameLabel (flash.display.FrameLabel) instances describing the frame labels within the movie clip's timeline. Each FrameLabel in the currentLabels array contains two properties: name, and frame. Name provides the name of the label and frame is the frame number on which it exists. currentLabel returns the name of the label associated with the current frame.
ActionScript Code:

var label:String = my_mc.currentLabel;


senocular 07-21-2006 12:36 PM

Multiple Arguments in trace()
 
As with previous versions of ActionScript, there exists a trace function for outputing messages into the Output panel in Flash. In ActionScript 1 and 2, trace accepted one argument that was outputed to the Output panel in Flash. In ActionScript 3, trace now accepts any number of arguments and outputs them each.
ActionScript Code:

trace(value1, value2, value3);



Note: You could get essentially the same effect in AS1 and AS2 using
ActionScript Code:

trace([value1, value2, value3]);


using an array ;)

senocular 07-21-2006 12:42 PM

Calling Event Handlers without Events
 
When you define event handlers in ActionScript 3, the functions need to accept 1 parameter of the type Event. When these methods are called by the events, those event objects are then passed into the handler.

If you have an event handler that you want to use as a normal function call, you can call that function with a new Event object passed into it like so:
ActionScript Code:

myHandler(new Event(someEventType));


However, that can be a hassle and a little confusing (plus you are creating an event that probably has nothing to do with the function). If you just want to be able to call the event handler without having to worry about that event but still have it work for calls coming from events, you can define the handler with your event parameter having a default value of null. This way you can call the function without an event but still have it work when the event is passed from an actual event call.
ActionScript Code:

public function myHandler(event:Event = null):void {...}
...
// call normally without event
myHandler();


Note: this will not work if your event handler relies on information from the event object.

senocular 07-22-2006 02:49 PM

URLRequest for URL Strings
 
Methods relying on URL strings in ActionScript 3 now use URLRequest (flash.net.URLRequest) instances instead of direct string values for URLs. URLRequest instances contain the following properties:
  • contentType:String
  • data:Object
  • method:String
  • requestHeaders:Array
  • url:String
which relates to the URL itself (specified in the url property).

For example, when using navigateToURL() (flash.net.navigateToURL) (getURL() replacement), instead of passing a string of the URL to navigate to, you use a URLRequest instance.
ActionScript Code:

var request:URLRequest = new URLRequest("http://www.adobe.com/");
navigateToURL(request);


masylum 07-25-2006 12:14 AM

eval() is removed...

senocular 07-25-2006 07:43 AM

XML vs. XMLDocument
 
XML has changed for ActionScript 3. The new way of dealing with XML revolves around E4X - ECMAScript's XML specification. This provides a different, more efficient interface for dealing with XML nodes and attributes. These are all associated with the new XML (top level XML) class.
ActionScript Code:

var myXML:XML = new XML(objectToConvert);


ActionScript Code:

var myXML:XML = <node />;



The old class, as it was used in ActionScript 1 and 2, is still around. However, it has been renamed to XMLDocument (flash.xml.XMLDocument). If you want to work with XML the way you did with AS1 and AS2, you would use XMLDocument instead of XML.
ActionScript Code:

var myXML:XMLDocument = new XMLDocument("<node />");


senocular 07-25-2006 07:56 AM

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

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

Example:
ActionScript Code:

var loader:URLLoader;
// ...
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, xmlLoaded);

var request:URLRequest = new URLRequest("file.xml");
loader.load(request);
//...
function xmlLoaded(event:Event):void {
    var myXML:XML = new XML(loader.data);
    //...
}


theHollow 07-25-2006 07:22 PM

Where can i download the Flash 9 Player application from? I don't want the plugin.

senocular 07-25-2006 08:16 PM

Quote:

Originally Posted by theHollow
Where can i download the Flash 9 Player application from? I don't want the plugin.

When you download Flex Builder, the Flex SDK, or Flash Alpha 9, you will also get standalone versions of the player (links in the first post).

NiñoScript 07-25-2006 10:21 PM

Quote:

Originally Posted by Senocular
trace(value1, value2, value3);


is there anyway so i can make a function (or class method) that accepts any number of arguments?

Krilnon 07-26-2006 01:14 AM

Quote:

Originally Posted by NiñoScript
is there anyway so i can make a function (or class method) that accepts any number of arguments?

Yep, use ... (rest). Senocular mentioned it in this post, and the documentation on it is here.

NiñoScript 07-26-2006 07:44 AM

wow, thats cool!

now, one more question... is there anyway to pass that array as single arguments for another function?

something like:
ActionScript Code:

function _trace(... rest):Array {
    trace(rest);
/* well... this is not a good example
    couse trace can accept an array as argument...
    but think about a function that can accept any number of Numbers
    but does nothing if you pass an Array to it */

    return rest;
}


senocular 07-26-2006 07:45 AM

use Function.apply() just like in AS1 and AS2

NiñoScript 07-26-2006 09:57 AM

ohh, i never used that :P
thanks ;)

senocular 07-29-2006 07:51 AM

is Operator (vs instanceof)
 
The is operator (is operator) is a new keyword that lets you check to see if an instance is of a certain object type. This works for ActionScript 3 class instances checked against class types as well as interfaces. Ex:
ActionScript Code:

var mySprite:Sprite = new Sprite();
trace(mySprite is Sprite);           // true
trace(mySprite is DisplayObject);    // true
trace(mySprite is IEventDispatcher); // true
 



The is operator is a replacement for instanceof (instanceof operator) from ActionScript 1 and 2. The is operator, however, is specific to AS3 classes and is used to check the inheritance specific to those classes. This will not work on dynamic classes created with AS1-style constructor functions. In that situation, you would use instanceof since instanceof checks the prototype chain of an instance as opposed to class inheritance (which is does). Because an AS3 class's class inheritance is mirrored in its prototype chain, this means that instanceof will also work for AS3 classes, though is is prefered then (and less typing!).

ActionScript Code:

var mySprite:Sprite = new Sprite();
trace(mySprite instanceof Sprite);           // true
trace(mySprite instanceof DisplayObject);    // true
trace(mySprite instanceof IEventDispatcher); // false - not in prototype chain
 


ActionScript Code:

var AS1StyleClass:Function = function(){}
AS1StyleClass.prototype = new MovieClip();

var as1Instance:* = new AS1StyleClass();
trace(as1Instance instanceof AS1StyleClass);    // true
trace(as1Instance instanceof MovieClip);        // true
trace(as1Instance is AS1StyleClass);    // true
trace(as1Instance is MovieClip);        // false - cant see prototype chain
 


senocular 07-29-2006 08:24 AM

Flash 9: Timelines as Classes
 
In Flash 9, you are able to associate all timelines with classes, including the root timeline. Movie clip timelines are associated with classes the same way as ActionScript 2 using the linkage dialog. The root timeline can be given a class association through the property inspector or through the publish settings (in ActionScript settings).

If you do not associate a timeline with a class, one is automatically created for that timeline by Flash. When this happens, variables become class variables, all named functions (declared using function functionName(){}) become methods of that class, and all scripts within the frames associated with methods that are automatically called when that frame is reached (minus the variable and method definitions). Because of this, you can only declare variables and named functions of any specific name for a function once. Variables you can redefine, but not redeclare. Functions (methods) are locked. Note: You cannot mix classes associated with timelines and timeline scripts.

The following timeline script in Flash 9
ActionScript Code:

var num:Number = 1;
function showNum():void {
    trace(num);
}
showNum();


essentially becomes the following AS3 class that gets associated with that timeline:
ActionScript Code:

package {
    class TimelineClass extends MovieClip {
       
        public var num:Number = 1;

        public function showNum():void {
            trace(this.num);
        }
        public function frame1():void {
            showNum();
        }
    }
}


senocular 07-29-2006 08:49 AM

RegExp: Email Validation
 
Here's an example of how one might validate email using ActionScript 3's Regular Expression class (Top level RegExp):

ActionScript Code:

function isValidEmail(email:String):Boolean {
    var emailExpression:RegExp = /^[a-z][\w.-]+@\w[\w.-]+\.[\w.-]*[a-z][a-z]$/i;
    return emailExpression.test(email);
}
//...
trace(isValidEmail("senocular@example.com")); // true
trace(isValidEmail("@example.com")); // false
trace(isValidEmail("senocular@example")); // false
trace(isValidEmail("seno\\cular@example.com")); // false
 


senocular 07-29-2006 09:16 AM

Render Event
 
ActionScript has long since relied on the enterFrame (onEnterFrame) event for time-based actions, especially animation and actions relating to frame playback. In comparison, Director's Lingo language has, not only an enterFrame event, but two other frame events, prepareFrame and exitFrame. Though ActionScript 3 has not aquired prepareFrame or exitFrame, it has gained a new frame event, render, or Event.RENDER (flash.events.Event.RENDER).

The render event in AS3 is a frame event that occurs after enterFrame (flash.events.Event.ENTER_FRAME) allowing one more chance to do what you need to do before the screen updates its display.

Unlike enterFrame, however, the render event will not be called unless the display object using it is attached to a stage (or in any display list attached to the stage). Also, render is not automatically called every frame, even if attached to the stage. In order for render to be called for the current frame, you must make a call to stage.invalidate() (flash.display.Stage.invalidate());

Ex:
ActionScript Code:

var sprite:Sprite = new Sprite();
stage.addChild(sprite);

sprite.addEventListener(Event.ENTER_FRAME, enterFrame);
sprite.addEventListener(Event.RENDER, render);
stage.addEventListener(MouseEvent.CLICK, click);

function enterFrame(event:Event):void {
    trace("enter frame");
}
function render(event:Event):void {
    trace("render");
}
function click(event:MouseEvent):void {
    trace("click");
    stage.invalidate();
}


Code:

Output:
enter frame
enter frame
enter frame
click
enter frame
render
enter frame
enter frame
enter frame
enter frame
...


senocular 07-29-2006 09:37 AM

XML: @ Operator for Attributes
 
E4X (XML used in ActionScript 3) has new operators to access values in XML. One operator is the @ operator which accesses attributes. It can be used in place of the attribute() (Top level XML.attribute()) method for obtaining attribute values. Ex:

ActionScript Code:

var myXML:XML = <user name="senocular" id="2867" />;
trace(myXML.attribute("name")); // senocular
trace(myXML.attribute("id")); // 2867
trace(myXML.@name); // senocular
trace(myXML.@id); // 2867
 



You can also use an asterisk (*) with the @ operator to get a list of all attributes associated with an XML node in the form of an XMLList object. This is equivalent to the attributes() (Top level XML.attributes()) method. Ex:

ActionScript Code:

var myXML:XML = <user name="senocular" id="2867" />;
var atts:XMLList;

atts = myXML.attributes();
trace(atts.toXMLString());
/* Output:
senocular
2867
*/

atts = myXML.@*;
trace(atts.toXMLString());
/* Output:
senocular
2867
*/


senocular 07-29-2006 09:40 AM

sorry about the delay this week; I got slammed at work :)

Deviant1853 07-30-2006 06:27 AM

Quote:

Originally Posted by senocular
ActionScript 3 lets you easily obtain any instances class name using a new function called getQualifiedClassName (flash.utils.getQualifiedClassName).
ActionScript Code:
var sprite:Sprite = new Sprite();
trace(getQualifiedClassName(sprite)); // "flash.display::Sprite"




You can also use the getQualifiedSuperclassName (flash.utils.getQualifiedSuperclassName) function to find its superclass
ActionScript Code:
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).
ActionScript Code:
trace(getDefinitionByName("flash.display::Sprite")); // [class Sprite]





With getDefinitionByName you should in theory be able to do some basic Object Reflection ? I guess you would have to do the method information manually though...

senocular 07-30-2006 08:44 AM

Quote:

Originally Posted by Deviant1853
With getDefinitionByName you should in theory be able to do some basic Object Reflection ? I guess you would have to do the method information manually though...

Did you see devonair's mention of describeType in the following post?

senocular 07-30-2006 10:13 AM

Event Propagation Support
 
ActionScript 3 now supports event propagation - the transference of a single event applying to multiple objects to each of those objects instead of one - in Display objects. In ActionScript 1 and 2, "Button" events (such as onPress, onRelease, etc.) handled by movie clips were not propagated to that movie clip's children. This means that though visually you were clicking on a child of a movie clip handling an onPress event, that onPress would never make it to the child because the parent movie clip handling the event would intercept it and prevent the propagation of the onPress event to that child.

Example; movie clip parent_mc contains child_mc:
ActionScript Code:

// AS1 and AS2
parent_mc.onPress = function(){
    trace("parent pressed");
}
parent_mc.child_mc.onPress = function(){
    trace("child pressed");
}

/* click child output:
parent pressed
*/


ActionScript Code:

// AS3
parent_mc.addEventListener(MouseEvent.CLICK, parentClick);
parent_mc.child_mc.addEventListener(MouseEvent.CLICK, childClick);

function parentClick(event:MouseEvent):void {
    trace("parent pressed");
}
function childClick(event:MouseEvent):void {
    trace("child pressed");
}

/* click child output:
child pressed
parent pressed
*/


In ActionScript 1 and 2, the child is never able to receive the event. In ActionScript 3, both movie clips are able to receieve it as the event is propagated to each movie clip to which it applies.

senocular 07-31-2006 08:06 AM

Get Sound Spectrum Information
 
Using ActionScript 3 you can now obtain sound spectrum information from audio played through Flash. This lets you create visualizations like those seen in popular in media player applications. The class that provides this information is the SoundMixer class (flash.media.SoundMixer). It's computeSpectrum method (static) places sound spectrum information in a ByteArray instance which can then be used to generate a visualization.
ActionScript Code:

// play sound...
var spectrumInfo:ByteArray = new ByteArray();
SoundMixer.computeSpectrum(spectrumInfo);
// spectrumInfo is now a byte array with sound spectrum info
 



All times are GMT -7. The time now is 02:02 PM.

Powered by vBulletin Version 3.5.4
Copyright ©2000 - 2006, Jelsoft Enterprises Ltd.
Copyright 2004 - kirupa.com