Anda di halaman 1dari 21

ActionScript 3®

migration cookbook
For Adobe® Flash® CS4 Professional
Table of Contents About this guide
This guide provides a quick introduction to migrating to ActionScript 3 from ActionScript 2.
4 Introduction It is targeted at designers and developers who have some experience scripting content
within Adobe Flash Professional. It does not require an understanding of
6 Top 5 misperceptions about ActionScript 3 object-oriented programming.

8 Top 5 benefits of ActionScript 3 This guide is intended as a quick guide and reference that complements the more
extensive migration resources and documentation available on the
10 Migration cookbook ActionScript 3 Technology Center:
11 Create an untyped variable
12 Create a typed variable
13 Create an untyped function adobe.com/go/as3migration
14 Create a typed function
15 Create an if/else statement
16 Create and loop through an array
17 Create a random number within a range
18 Access root/main timeline of your content How to use this guide
19 Handling button interactions
20 Open a URL This guide can be used as both a high-level introduction to ActionScript 3, and a reference
21 Listen for key presses for accomplishing frequent tasks when creating content in Flash Professional. The guide is
22 Dynamically attach a MovieClip from the library broken down into a number of sections:
24 Dynamically create and draw on a MovieClip
26 Dynamically set the color of a MovieClip Introduction: Provides a high-level introduction to ActionScript 3
27 Dynamically swap MovieClip depths
28 Dynamically create and loop through MovieClip instances Top misperceptions: Dispels some of the top misperceptions around ActionScript 3
32 Play an embedded sound
34 Dynamically load and play a sound Top benefits: Lists some of the top benefits of ActionScript 3
35 Dynamically load and display an image
36 Load and read XML Migration cookbook: Shows how to do common tasks in ActionScript 3

38 Notes

©2009 Adobe Systems Incorporated. All rights reserved. Adobe, the Adobe logo, ActionScript, the Adobe Flash This work is released under a Creative Commons Attribution-Noncommercial
logo, Flash, Pixel Bender, are either registered trademarks or trademarks of Adobe Systems Incorporated in the 3.0 Unported License.
United States and/or other countries. Printed in the USA. 95012173 03/09 creativecommons.org/licenses/by-nc/3.0

2 3
ActionScript 3 migration cookbook adobe.com/go/as3migration
What is ActionScript 3? Note that because the MovieClip class is dynamic, if you use the old underscore
property names in ActionScript 3, you will not get an error and the property will
ActionScript 3 is the most current version of the language used for scripting and not be set correctly.
programming interactive content for the Adobe Flash Platform. The Flash Platform
is a complete system of integrated tools, frameworks, clients and servers that can be Void has changed to void
used to create and deploy Web applications, content and video that run consistently In ActionScript 2, Void is used to denote when a function does not return anything.
across operating systems and devices, leveraging the ubiquity of Adobe Flash Player In ActionScript 3, the term is now void (all lowercase).
and Adobe AIR®.
Alpha value ranges
ActionScript 3 was created in order to provide significant performance improvements In ActionScript 2, alpha/transparency values are expressed in a range between 0 and 100.
over ActionScript 2, and to make developing applications easier and more maintainable. In ActionScript 3, alpha values are now expressed in a range between 0.0 and 1.0.
However, even though ActionScript 3 was largely targeted at rich Internet application
development, its strengths and benefits can also be leveraged when creating more Events
expressive and creative content in Flash Professional, such as animations or ActionScript 3 includes a built-in event model which is used throughout the language.
motion graphics. The advantages of the new API include a standard way to handle events, the ability for
multiple items to listen to the same event, and correct scoping of event handlers.
In general, ActionScript 3 can be broken down into two main parts: the core language, The syntax for specifying event handlers has changed and you can no longer place
and the programming APIs. The semantics of the core language are not much different event handles directly on symbols within Flash CS4 Professional.
from ActionScript 2 and should not present much of a learning curve. However, the Flash
Player APIs have undergone some significant changes, which means that some common Common compiler errors when migrating to ActionScript 3
tasks are done differently in ActionScript 3. This reference focuses on some of the new
ActionScript 3 APIs which are used often, but are different enough from their Below are a some compile-time errors that are common when migrating content
ActionScript 2 counterparts to potentially cause confusion. to ActionScript 3.

While learning the new APIs can be frustrating at times, the improved consistency 1067: Implicit coercion of a value of type Number to an unrelated type String.
between APIs in ActionScript 3 means that knowledge learned while using one particular You are trying to store a value of one type into a variable that is set to store another type.
API can be applied to learning other APIs. It is this improved consistency between APIs
which can significantly reduce the migration and learning curve for ActionScript 3. For example:

ActionScript 3 migration gotchas var s:String;


var n:Number = 5;
n = s;
Below is a list of changes that may trip you up when you first begin working with
ActionScript 3. You can find examples of all of the items in the cookbook entries.
1136: Incorrect number of arguments. Expected 1.
Use of underscore in MovieClip property names You are calling a function without passing in the correct number of arguments.
In ActionScript 3, the use of the underscore (“_”) at the beginning of property names for the
MovieClip object have been removed in order to provide greater consistency with the rest 1152: A conflict exists with inherited definition flash.display:DisplayObject.transform
of the ActionScript APIs. For example, the ActionScript 2 _x, _y, _alpha and _rotation in namespace public.
properties have been changed to x, y, alpha, and rotation in ActionScript 3. You have a variable name that conflicts with a built-in property name
(most likely contained within the DisplayObject class).

4 5
ActionScript 3 migration cookbook adobe.com/go/as3migration
1. ActionScript 3 is difficult to learn
ActionScript 3 is no more difficult to learn than any other programming or scripting
language. If you are familiar with ActionScript 2, the language semantics are pretty
much the same, although you will need to learn new ways of doing some common tasks.

Because the ActionScript 3 APIs are more consistent, learning one new concept and
API applies to multiple APIs, making it easier to use newly found knowledge to learn
new features and functionality.

2. ActionScript 3 is only for object-oriented programmers


ActionScript 3 can be used for both class-based, object-oriented programming, as well
as timeline-based scripting. You can use it in whichever way is the most comfortable
Top for you or makes the most sense for your project.

misperceptions 3. Targeting ActionScript 3 reduces the Flash Player base that you can target
As of December 2008, content targeted for Flash Player 9, the first version that supported
ActionScript 3, can be viewed by 98.6% of computers on the Internet.
about ActionScript 3
4. You can’t write code on the timeline with ActionScript 3
You can place code on the timeline just as you can with ActionScript 1 and 2.

5. ActionScript 2 development is faster than ActionScript 3


While some tasks can require more code in ActionScript 3 than in ActionScript 2, overall
development and maintenance time should be the same or less than in ActionScript 2.0
due to improved debugging and better compile-time error catching. Basically, in some
cases there may be more code, but it will be much easier to find errors.

6 7
ActionScript 3 migration cookbook adobe.com/go/as3migration
1. Achieve greater performance
ActionScript 3 was written from the ground up with performance in mind. Depending
on the content, you can see a significant increase in performance. This means that
your existing content may run smoother, and your new content can do more, while
using the same amount of CPU resources.

2. Leverage new Flash Player APIs


Adobe Flash Player 9 and 10 includes a ton of new features which can only be used
through ActionScript 3. These include much easier XML APIs via E4X, more advanced
display list manipulation, or doing advanced image manipulation with Pixel Bender™ filters.

As a general rule, new ActionScript-based features added in the future will only be
Top available via ActionScript 3.

benefits
3. Leverage community libraries and APIs
Almost all of the major new libraries released by the community are built with
ActionScript 3, and include everything from the Papervision3D full 3D engine
library to Grant Skinner’s Gtween animation library.
of ActionScript 3
4. Troubleshoot code more easily
The ActionScript 3 compiler provides options for much stricter error checking, which
means it is more likely you are going to find bugs and errors before you even begin to run
your content. When you do find errors, you can take advantage of some of the new and more
advanced debugging features to track them down (and of course, you can still use trace()).

5. Develop content for multiple platforms


ActionScript 3 is the standard language used across the Adobe Flash Platform. Moving
forward, it is the language that Adobe will focus on supporting in existing and new players
(like Adobe AIR), servers, and products. Flash Player 10 supports ActionScript 3, and its use
is required for developing for Adobe Flex and Adobe AIR content. In addition, Adobe is
working on updating its mobile runtimes to ActionScript 3.

In the future, you can expect that new Flash Platform products, runtimes, and services from
Adobe will use ActionScript 3.

8 9
ActionScript 3 migration cookbook adobe.com/go/as3migration
cookbook: Create an untyped variable

Task: You need to create a variable to store a value.


Solution: Use the var keyword to declare a variable.

ActionScript 2

var s = "I am a String";


var i = 5;

migration

cookbook ActionScript 2.0 to ActionScript 3.0

ActionScript 3

var s = "I am a String";


var i = 5;

Note: Just as in ActionScript 2, you use the var keyword only the first time you declare the variable.

10 11
ActionScript 3 migration cookbook adobe.com/go/as3migration
cookbook: Create a typed variable cookbook: Create an untyped function

Task: You need to create a variable to store a specific type of value. Task: You need to create a function that takes an argument and then call it.
Solution: Use the var keyword and specify the variable type. Solution: Use the function keyword to create a function that takes a variable.

ActionScript 2 ActionScript 2

var s:String = "I am a String"; function foo(bar)


var i:Number = 5; {
trace(bar);
}

foo("hello");

ActionScript 3 ActionScript 3

var s:String = "I am a String"; function foo(bar)


var i:Number = 5; {
trace(bar);
}

foo("hello");

Note: Once you type the variable, you can only store data of that type in the variable. Note: Unlike in ActionScript 2, in ActionScript 3 if you attempt to call the function without any arguments,
you will get an error.
For example, the following would throw an error:
For example, he following would throw an error:
var s:String = "I am a String";
var i:Number = 5; function foo(bar)
{
s = i; trace(bar);
}

because you are trying to store a Number in a variable which you specified was a String.
foo();

The advantage of typing variables is that, in general, it makes your code a little easier to read, the player can
run your code faster, and the compiler can find some errors when you compile your content.

All of the examples in this cookbook use typed variables.

12 13
ActionScript 3 migration cookbook adobe.com/go/as3migration
cookbook: Create a typed function cookbook: Create an if/else statement

Task: You need to create a function that specifies the type of its arguments, as well Task: You need to branch your code depending on a value in your content.
as its return type.
Solution: Use an if/else statement to determine what code to run.
Solution: Use the function keyword and type identifiers to create a function that
takes and returns a typed value.

ActionScript 2 ActionScript 2

function foo(bar:String):Void var value:Number = 5;


{
trace(bar); if(value > 5)
} {
trace("value is greater than 5");
foo("hello"); }
else if(value < 5)
{
trace("value is less than 5");
}
else
{
trace("value equals 5");
}

ActionScript 3 ActionScript 3

function foo(bar:String):void var value:Number = 5;


{
trace(bar); if(value > 5)
} {
trace("value is greater than 5");
foo("hello"); }
else if(value < 5)
{
trace("value is less than 5");
}
else
{
trace("value equals 5");
Note: We specify the return type as void, which means that the function does not return a value. }
Also note that in ActionScript 3 the usage is void, and not Void as in ActionScript 2.

If you try to call the function in ActionScript 3 and pass it a Number instead of a String, you
will get an error.
Note: You can use the if statement without the else if, and else parts.

14 15
ActionScript 3 migration cookbook adobe.com/go/as3migration
cookbook: Create and loop through an Array cookbook: Create a random number within a range

Task: You need to create an Array and loop through its values. Task: You need to create a random absolute number between 0 and 10.
Solution: Use a for loop to loop through the Array. Solution: Use new Math APIs to generate a random number.

ActionScript 2 ActionScript 2

var a:Array = ["a", "b", "c", "d"]; var max:Number = 10;


var randInRange:Number = random(10 + 1);
var len:Number = a.length;
trace(randInRange);
for(var i:Number = 0; i < len; i++)
{
trace(a[i]);
}

ActionScript 3 ActionScript 3

var a:Array = ["a", "b", "c", "d"]; var rand:Number = Math.random();


var max:Number = 10;
var len:Number = a.length; var randInRange:Number = Math.round(rand * max);

for(var i:Number = 0; i < len; i++) trace(randInRange);


{
trace(a[i]);
}

Note: You can also use the Array constructor and push method to populate an Array like so: Note: The Math.random and Math.round functions are available in ActionScript 2, but are included
here for completeness.
var a:Array = new Array();
a.push("a");
a.push("b");
a.push("c");
a.push("d");

16 17
ActionScript 3 migration cookbook adobe.com/go/as3migration
cookbook: Access root/main timeline of your content cookbook: Handling button interactions

Task: You need to access the root / main timeline of your content. Task: You need to determine when the user interacts with a button.
Solution: Use the root property to access the root timeline of your content. Solution: Listen for events broadcast by the button.

ActionScript 2 ActionScript 2

//function on main timeline function onButtonRelease():Void


{
function foo():Void trace("button was clicked");
{ }
trace("foo");
} function onButtonRollOver():Void
{
//called from anywhere in content trace("button was moused over");
_root.foo(); }

my_button.onRelease = onButtonRelease;
my_button.onRollOver = onButtonRollOver;

ActionScript 3 ActionScript 3

//function on main timeline function onButtonClick(event:MouseEvent):void


{
function foo():void trace("button was clicked");
{ }
trace("foo");
} function onMouseOver(event:MouseEvent):void
{
//called from anywhere in SWF trace("button was moused over");
MovieClip(root).foo(); }

my_button.addEventListener(MouseEvent.CLICK, onButtonClick);
my_button.addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);

Note: In ActionScript 2 _root always refers to the main timeline of the main SWF. In ActionScript 3, the root
property refers to the main timeline of the SWF in which the content originates. In most cases, these will
be the same in either version of ActionScript. The main exception is where the property is being called from Note: Both examples assume there is a button symbol instance named "my_button" on the same timeline
within a SWF that has been loaded into another SWF. In ActionScript 2 _root will refer to the main timeline as the code.
of the main SWF (that loaded the other SWF). In ActionScript 3 the root property refers to the main timeline
of the loaded SWF (and not the timeline of the SWF which loaded the other SWF).

The root property is only available in DisplayObject instances (such as MovieClip, Sprite and Button).

18 19
ActionScript 3 migration cookbook adobe.com/go/as3migration
cookbook: Open a URL cookbook: Listen for key presses

Task: You need to open a URL in a new browser window. Task: You need to detect when the user presses a key.
Solution: Use navigateToURL to open URLs in ActionScript 3. Solution: Listen for the KeyboardEvent.KEY_UP event.

ActionScript 2 ActionScript 2

getURL("http://www.adobe.com", "_blank"); function onKeyDown():Void


{
var code:Number = Key.getCode();
var char:String = String.fromCharCode(code);
trace("Key Down : code : " + code + " char : " + char);
}

Key.addListener(this);

ActionScript 3 ActionScript 3

var url:URLRequest = new URLRequest("http://www.adobe.com"); function onKeyDownHandler(event:KeyboardEvent):void


navigateToURL(url, "_blank"); {
var code:uint = event.keyCode;
var char:String = String.fromCharCode(code);
trace("Key Down : code : " + code + " char : " + char);
}

stage.addEventListener(KeyboardEvent.KEY_UP, onKeyDownHandler);

20 21
ActionScript 3 migration cookbook adobe.com/go/as3migration
cookbook: Dynamically attach a MovieClip from the library

Task: You need to dynamically attach a MovieClip from the library.


Solution: Use the MovieClip constructor to attach a symbol from the library.

ActionScript 2

attachMovie("my_clip", "clip", 10);

clip._x = 100;
clip._y = 100;
clip._alpha = 50;

ActionScript 3

var clip:MovieClip = new my_clip();

clip.x = 100;
clip.y = 100; Setting the class name for a MovieClip symbol
clip.alpha = .5; for use in ActionScript 3

addChild(clip);

Note: In ActionScript 2 the linkage ID , “my_clip” is set in the library for the MovieClip, whereas in
ActionScript 3, the class name , “my_clip” is set.

22 23
ActionScript 3 migration cookbook adobe.com/go/as3migration
cookbook: Dynamically create and draw on a MovieClip

Task: You need to dynamically create a MovieClip, place it on the Stage and draw on it.
Solution: Use the MovieClip constructor to create the MovieClip and then draw into its
graphics property.

ActionScript 2 ActionScript 3

function drawCircle(target_mc:MovieClip, radius:Number, fillColor:Number, fillAlpha:Number) var clip:MovieClip = new MovieClip();


{
var x:Number = radius; addChild(clip);
var y:Number = radius;
with (target_mc) clip.x = 250;
{ clip.y = 250;
beginFill(fillColor, fillAlpha);
moveTo(x + radius, y); clip.graphics.lineStyle(2, 0xF89950);
curveTo(radius + x, Math.tan(Math.PI / 8) * radius + y, Math.sin(Math.PI / 4) * clip.graphics.beginFill(0xFFe0AC, .5);
radius + x, Math.sin(Math.PI / 4) * radius + y); clip.graphics.drawCircle(0, 0, 200);
curveTo(Math.tan(Math.PI / 8) * radius + x, radius + y, x, radius + y);
curveTo(-Math.tan(Math.PI / 8) * radius + x, radius+ y, -Math.sin(Math.PI / 4) *
radius + x, Math.sin(Math.PI / 4) * radius + y);
curveTo(-radius + x, Math.tan(Math.PI / 8) * radius + y, -radius + x, y);
curveTo(-radius + x, -Math.tan(Math.PI / 8) * radius + y, -Math.sin(Math.PI / 4) *
radius + x, -Math.sin(Math.PI / 4) * radius + y);
curveTo(-Math.tan(Math.PI / 8) * radius + x, -radius + y, x, -radius + y);
curveTo(Math.tan(Math.PI / 8) * radius + x, -radius + y, Math.sin(Math.PI / 4) *
radius + x, -Math.sin(Math.PI / 4) * radius + y);
curveTo(radius + x, -Math.tan(Math.PI / 8) * radius + y, radius + x, y);
endFill();
}
}

createEmptyMovieClip("circle_mc", 10);
circle_mc._x = 250;
circle_mc._y = 250;
drawCircle(circle_mc, 250, 0xFFe0AC, 50);

Circle dynamically drawn in ActionScript 3.0

Note: In ActionScript 2 drawing is done directly on the MovieClip, whereas in ActionScript 3, it is done on
the graphics property of the MovieClip.

24 25
ActionScript 3 migration cookbook adobe.com/go/as3migration
cookbook: Dynamically set the color of a MovieClip cookbook: Dynamically swap MovieClip depths

Task: You need to dynamically set the color of a MovieClip. Task: You need to dynamically swap the depths of two MovieClip instances.
Solution: Use the colorTransform property to set the color. Solution: Use the swapChildren API.

ActionScript 2 ActionScript 2

var clip:MovieClip = attachMovie("circle_clip", "circle_clip", 1); var clip_1:MovieClip = attachMovie("blue_square", "clip_1", 1);
clip._x = 100;
clip_1._x = 100;
clip._y = 100; clip_1._y = 100;

function onStageClick():Void var clip_2:MovieClip = attachMovie("green_square", "clip_2", 2);


{
clip_2._x = 115;
var c:Color = new Color(clip); clip_2._y = 115;
c.setRGB(Math.random() * 0xFFFFFF);
} function onStageClick():Void
{
clip_1.swapDepths(clip_2);
onMouseUp = onStageClick; }

onMouseUp = onStageClick;

ActionScript 3

var clip:MovieClip = new circle_clip(); ActionScript 3


clip.x = 100;
clip.y = 100; var clip_1:MovieClip = new green_square();

clip_1.x = 100;
addChild(clip); clip_1.y = 100;

function onStageClick(event:MouseEvent):void var clip_2:MovieClip = new blue_square();


{
clip_2.x = 115;
var c:ColorTransform = new ColorTransform(); clip_2.y = 115;
c.color = (Math.random() * 0xFFFFFF);
clip.transform.colorTransform = c; addChild(clip_1);
addChild(clip_2);
}

stage.addEventListener(MouseEvent.CLICK, onStageClick);
stage.addEventListener(MouseEvent.CLICK, onStageClick);
function onStageClick(event):void
{
swapChildren(clip_1, clip_2);
}
Note: Math.random * 0xFFFFFF creates a random color.

26 27
ActionScript 3 migration cookbook adobe.com/go/as3migration
cookbook: Dynamically create and loop through MovieClip instances

Task: You need to dynamically create and then loop through MovieClips.
Solution: Use DisplayList and DisplayListContainer container methods.

ActionScript 2 ActionScript 3

var numItems:Number = 250; var container:MovieClip = new MovieClip();


var stageWidth:Number = Stage.width; addChild(container);
var stageHeight:Number = Stage.height; var numItems:Number = 250;
var stageWidth:Number = stage.stageWidth;
createEmptyMovieClip("container", 2); var stageHeight:Number = stage.stageHeight;
container.height = stageHeight;
container.width = stageWidth; function initClips():void
{
function initClips():Void var c:MovieClip;
{ for(var i:Number = 0; i < numItems; i++)
var clipName:String; {
for(var i:Number = 0; i < numItems; i++) c = new circle_mc();
{ randomizeClip(c);
clipName = "circle_clip_" + i; container.addChild(c);
container.attachMovie("circle_mc", clipName, i + 5 ); }
randomizeClip(container[clipName]); }
}
} function randomizeClip(clip:MovieClip):void
{
function randomizeClip(clip:MovieClip):Void clip.x = Math.random() * stageWidth;
{ clip.y = Math.random() * stageHeight;
clip._x = random(stageWidth);
clip._y = random(stageHeight); clip.scaleX = Math.random() * 2;
clip._xscale = random(200); clip.scaleY = Math.random() * 2;
clip._yscale = random(200);
var c:ColorTransform = new ColorTransform();
var c:Color = new Color(clip); c.color = (Math.random() * 0xFFFFFF);
c.setRGB(Math.random() * 0xFFFFFF); clip.transform.colorTransform = c;
clip._alpha = random(100);
} clip.alpha = Math.random();
}
function onEnterFrame():Void
{ function onEnterFrame(event:Event):void
var c:MovieClip; {
for(var i:Number = 0; i < numItems; i++) var c:MovieClip;
{ for(var i:Number = 0; i < numItems; i++)
c = container["circle_clip_" + i]; {
randomizeClip(c); c = MovieClip(container.getChildAt(i));
} randomizeClip(c);
} }
}
initClips();
initClips();
addEventListener(Event.ENTER_FRAME, onEnterFrame);

28 29
ActionScript 3 migration cookbook adobe.com/go/as3migration
Dynamically created MovieClip instances from the example on previous page

30 31
ActionScript 3 migration cookbook adobe.com/go/as3migration
cookbook: Play an embedded sound

Task: You need to play a sound contained within your content and set its volume.
Solution: Use the Sound, SoundChannel, and SoundTransform classes to play and
manipulate sounds.

ActionScript 2

function onSoundComplete():Void
{
trace("sound is completed");
} Setting the class name for an embedded
sound for ActionScript 3
var my_sound:Sound = new Sound();
my_sound.attachSound("beep_id");
my_sound.setVolume(50);

my_sound.onSoundComplete = onSoundComplete;

my_sound.start();

ActionScript 3

function onSoundComplete(event:Event):void
{
trace("sound is completed");
}

var my_sound:Sound = new beep_id();


var sTransform:SoundTransform = new SoundTransform();
sTransform.volume = .5;

var channel:SoundChannel = my_sound.play();


channel.soundTransform = sTransform;
channel.addEventListener(Event.SOUND_COMPLETE, onSoundComplete);

32 33
ActionScript 3 migration cookbook adobe.com/go/as3migration
cookbook: Dynamically load and play a sound cookbook: Dynamically load and display an image

Task: You need to dynamically load and play an MP3 file. Task: You need to dynamically load and display an image.
Solution: Use the Sound.load API to load and control the sound. Solution: Use the Loader class to load the image.

ActionScript 2 ActionScript 2

var sound = new Sound(); createEmptyMovieClip("loader", 10);

sound.loadSound("sound.mp3", true);
loader.loadMovie("image.png");

loader._x = 100;
loader._y = 100;
loader._rotation = 20;
loader._alpha = 50;

ActionScript 3 ActionScript 3

var url = new URLRequest("sound.mp3"); var request:URLRequest = new URLRequest("image.png");


var loader:Loader = new Loader();
var sound = new Sound();
loader.load(request);
sound.load(url);
sound.play(); loader.x = 100;
loader.y = 100;
loader.rotation = 20;
loader.alpha = .5;

addChild(loader);

34 35
ActionScript 3 migration cookbook adobe.com/go/as3migration
cookbook: Load and read XML

Task: You need to load and read an XML file.


Solution: Use the URLLoader API to load the XML and the E4X XML API to parse it.

ActionScript 2 ActionScript 3

function onXMLLoad(success:Boolean):Void onXMLLoad(event:Event):void


{ {
trace(this); var xml:XML = new XML(event.target.data);
trace(xml);
trace("Number of Contacts : " + this.firstChild.childNodes[0].childNodes.length);
trace("Number of Contacts : " + xml..person.length());
var firstPerson:XMLNode = this.firstChild.childNodes[0].childNodes[0]; trace("First contact’s favorite food : " + xml.contacts.person[0].favoriteFood);
var nodes:Array = firstPerson.childNodes; }
var nodeLen:Number = nodes.length;
var loader:URLLoader = new URLLoader();
var node:XMLNode; var url:URLRequest = new URLRequest("contacts.xml");
var favoriteFood:String; loader.addEventListener(Event.COMPLETE, onXMLLoad);
for(var i:Number = 0; i < nodeLen; i++)
{ loader.load(url);
node = nodes[i];

if(node.nodeName == "favoriteFood")
{
favoriteFood = node.firstChild.nodeValue;
}
}

trace("First contact’s favorite food : " + favoriteFood); Note: Both examples use the following XML contained in a file called contacts.xml:
}

var my_xml:XML = new XML(); <xml>


<contacts>
<person>
my_xml.onLoad = onXMLLoad; <name>Mike Chambers</name>
my_xml.ignoreWhite = true; <favoriteFood>Bacon</favoriteFood>
my_xml.load("contacts.xml");
</person>
<person>
<name>John Doe</name>
<favoriteFood>Pez</favoriteFood>
</person>
</contacts>
</xml>

Note: in the ActionScript 3 example this in the onXMLLoad function refers to the timeline that contains
the code, while in the ActionScript 2 example, this refers to the XML object instance.

36 37
ActionScript 3 migration cookbook adobe.com/go/as3migration
notes: notes:

38 39
ActionScript 3 migration cookbook adobe.com/go/as3migration
Online resources and information

ActionScript® 3 migration resources Designer and developer centers

ActionScript® 3 Migration Center Adobe Flash® developer center


adobe.com/go/as3migration adobe.com/go/flashdevcenter

ActionScript® 3 Migration Reference ActionScript® developer center


adobe.com/go/as2toas3 adobe.com/go/flash_as3

Adobe design center


Forums adobe.com/designcenter/

ActionScript® 3 Forum
adobe.com/go/as3_forums
Product technology pages
Adobe Flash® Forum
adobe.com/go/flash_forums Flash Player
adobe.com/go/flash

Documentation Adobe Creative Suite® 4


adobe.com/go/creativesuite
ActionScript® 3 API Reference
adobe.com/go/flash_docs

Adobe Flash® CS4 Professional Support Center


adobe.com/support/flash/

Anda mungkin juga menyukai