Archive | Flash Tutorials

Create A Flash Countdown Timer in AS3 Using A Class

Create A Flash Countdown Timer in AS3 Using A Class

Due to the popularity of one of my earlier posts, I’ve decided to extend the topic with a helpful Countdown Timer class. This handy utility provides a flexible and easy way to tie in countdown timer functionality into just about any design. It is designed to handle the grunt work of developing a Countdown Timer. It is not meant to replace the Countdown Timers available to the Flash community. It is purely meant to easily implement Countdown Timer functionality to you own custom design without reinventing the wheel.

Features Include:

  • Easily define a new Countdown Timer instance
  • Access to the countdown’s remaining days, hours, minutes and seconds
  • Easily update the target end date
  • Custom events that trigger upon Countdown updating and on complete

Getting started creating a fresh Countdown Timer

Implementing your new countdown timer design will require minimal ActionScript as the this utility will handle key events and updating of the remaining time.  All you need to implement this countdown functionality is a design and some time.  Enjoy!

Step 1: Importing the necessary classes

In order to use this utility within your Flash file, you would need to import the following two classes: CountdownTimer.as and CountdownEvent.as. Note: Make sure that the classes are local to your .fla file or if you are more comfortable modifying your ActionScript settings to accommodate the location of the classes, feel free doing so.

// Importing of the CountdownTimer Class
import com.flashspeaks.utils.CountdownTimer;
// Importing the CountdownEvent (used to update and notify upon countdown completion)
import com.flashspeaks.utils.CountdownEvent;

Step 2: Creating a new Countdown Timer Instance

Creating a new instance of the Countdown Timer is as easy as defining a new Countdown Timer instance and providing the target end date within the parameter. The values needed are the target year, month, and day. There are also optional hour and second values just in case you needed extreme flexibility in the target end date.

// This creates a new CountdownTimer instance and sets it target end date
var myCountdown:CountdownTimer = new CountdownTimer(year, month, day, hour(optional), second(optional));

Step 3: Retrieve the remaining days, hours, minutes, and seconds

In order to provide flexibility, I have provided public properties to obtain the days, hours, minutes, and seconds remaining separately allowing you to determine how you would like to display the remaining time. There is also a property called time that will return the remaining time as a whole number separated by colons. (00:00:00:00)

In order to retrieve the time, a new COUNTDOWN_UPDATE event listener needs to be established as it will be mapped to a function that will update upon every tick. It can be easily done like so.

myCountdown.addEventListener(CountdownEvent.COUNTDOWN_UPDATE, onCountdownUpdate, false, 0, true);

function onCountdownUpdate(e:CountdownEvent):void {
 // Update on screen visuals like text
}

Countdown has expired…what to do?

One of the requested key features was a way to easily determine when the countdown had expired. Some wanted to load a new timer, change on screen text to read 00:00:00:00 ,etc. Setting this up using CountdownTimer is fairly easy. To do so, you would essentially create a new COUNTDOWN_COMPLETE event listener and supplying what it is that you would like to occur within the event handler function. Check it out below!

countdown.addEventListener(CountdownEvent.COUNTDOWN_COMPLETE, onCountdownComplete, false, 0, true);
function onCountdownComplete(e:CountdownEvent):void {
 // Countdown finished...
 // HAPPY NEW YEAR
}

Change the target end date on the fly

Another huge request was to provide a solution to easily update the target end date via run-time. CountdownTimer provides a function called updateEndDate(new Date()) which allows you to simply provide a new target end date through its parameter. Your on screen visuals will automatically update to accommodate the new end date.

For example, let’s say you wanted to add a month to the target end date every time that it has expired you can to so by simply adding one month to current month within the onCountdownComplete event handler.

Complimentary Flash Countdown Timer design

What’s good Countdown Timer functionality without a good Countdown Timer design? Here’s a complimentary design that I will be providing with the download. It includes the example source and provides all of the source from this tutorial. Feel free to implement your own design! I’d love to see them!

Get Adobe Flash player

Download example files

Posted in Custom Classes, Flash Tutorials0 Comments

Creating a Button Using FlashEff 2

Creating a Button Using FlashEff 2

In a previous post, I introduced the release of FlashEff 2 as an innovative Flash animation tool. In an attempt to prove my point, I am going to demonstrate how you can use FlashEff 2 to create a button using a MovieClip object.

OK, I know some of you might be thinking, a button? Well, creating a button in AS3 can be somewhat of a pain. After you get through creating your buttons, adding its functionality along with creating its appropriate event listeners; this process can get very old and tiring. Since FlashEff is here to simplify your workflow, why not let FlashEff handle your button’s functionality, animation and event listener creation.

Using Button Mode

In FlashEff 2, you can edit a button using its Button mode. This mode will allow you to assign your button some actions like following an URL, calling a function, or even going to a different frame whenever it gets clicked. All this without one single line of ActionScript. Here’s how!

Creating a Button Object

I am going to take a button graphic/design and create a MovieClip out of it. Once created, I will go into my Component Panel and drag a copy of the FlashEff2Button component onto my newly created MovieClip. One other great thing about FlashEff is that upon dragging a copy of its component onto the target object it will snap to the target’s 0,0 position.

FlashEff: Snap to Object

Now it is time to toy around with the FlashEff Panel.

Using the FlashEff Panel

The FlashEff Panel is where all of the magic happens. Here you can select any of the preset effects/animations that an object can have. Once you’ve added a preset, you can then preview an example of it via the live preview feature of the panel.  Take it for a test drive.

FlashEff Panel

Adding my Button Effect/Animation

In this example, I will select the “HappyTurn” preset. Now, if I wanted to I can modify the presets; allowing me to then save my own “custom” preset.  (Feature available only if you have the Premium Plus license) You can also adjust the tween type and speed for the up, over, and down button states. Just to keep things simple, I won’t be doing any of that.

FlashEff: Happyturn Preset

Adding Commands to the Button

FlashEff’s Button mode comes equipped with its assortment of commands that you can trigger upon press. They include adding a sound, calling a function, going to a keyframe, navigating to a URL, playing back a sound, and switching objects. Also, you can even stack these commands which will allow you to trigger a sound, call a function, and navigate to a URL on one press.

In this example, I will be adding a sound playback on press along with an event to navigate to a URL upon double clicking the button object. When attaching a sound you can identify that sound through a linkage ID or path.

FlashEff: Custom Commands

Overview

Below, you can find the final result of this mini demo.  Basically, the button, upon rollover, triggers the HappyTurn animation, then on press a click sound will trigger.  Now, if you double-click it will take you to the designated destination, Google’s homepage.  The custom possibilities are endless.  The more you use FlashEff the more situations you can picture yourself using the tool to simplify your project’s workflow.  To learn more on what FlashEff can accomplish, visit FlashEff.com.

Get Adobe Flash player

FlashEff 2 Giveaway Opportunity

In the upcoming days, you are going to have the opportunity of winning 1 of 2 FlashEff 2 unlimited premium licenses.  Stay tuned…

Posted in Flash Tools, Flash Tutorials0 Comments

ActionScript 1:1 – Getting Intimate With ActionScript 3.0

ActionScript 1:1 – Getting Intimate With ActionScript 3.0

Struggling to get our foot off the ground with getting more intimate with ActionScript 3.0?

Doug Winnie has kicked off a series, ActionScript 1:1, which is designed for animators and designers using Flash CS4 who want to take their work to the next level but need some guidance adding custom interactivity using ActionScript 3.0.

These videos are aimed at Flash Designers looking to strengthen their knowledge of ActionScript 3.0.  We all have to start somewhere when learning to use ActionScript 3.0 and this series is great way to get that train moving along.

Below are all the episodes in the series.  You can also find Doug’s videos as a channel on Adobe TV and iTunes.  Enjoy!

Welcome to ActionScript 3

Welcome to ActionScript 3.0

Doug Winnie gives an overview of his new series in which you will learn the fundamentals of ActionScript 3.0. Get up and running in Flash Professional using ActionScript 3.0.

Working with the Actions Panel

Working with the ActionScript Panel

Understand how to use the Actions panel and use the trace statement. Doug Winnie walks you through the code to control objects created in Flash.

Accessing Object Parameters

Accessing Object Parameters

Doug Winnie demonstrates how to access properties of an object such as size and location by using instance properties with ActionScript, sending messages to the output console.

Changing Object Parameters

Changing Object Parameters

In order to manipulate objects, Doug Winnie uses the assignment operator in ActionScript 3.0 to instantaneously overwrite values initially assigned in Flash.

Exploring Named Library Assets

Exploring Named Library Assets

Dive deeper with the Library panel and learn more about how to name instances on the stage, and how to use the Linkage panel to name objects in the Library panel.

Adding Named Objects to the Stage

Adding Named Objects to the Stage  // Image

In this video, Doug Winnie teaches you how to use ActionScript to dynamically add objects to the stage using code and the DisplayStack.

Working with Comments

Working with Comments

You can use comments to document your ActionScript code for other Developers to use. Doug’s tutorial sums up the benefit of building up good coding practices.

Fundamentals of Functions

Fundamentals of Functions

Doug Winnie provides an introduction to functions and explains how to efficiently use them in ActionScript by grouping commonly used tasks together as a named function.

Accepting Values in Functions

Accepting Values in Functions

Doug continues his tutorial on how to efficiently use functions with ActionScript. With functions you can customize their functionality by assigning parameters and values.

Returning Values from Functions

Returning Values from Functions

Doug Winnie wraps up his lesson on functions by explaining how to retrieve results for the output panel with the return statement.

Mathematical Operators

Mathematical Operators

Doug Winnie teaches the basics of calculating mathematical operations in ActionScript code, including commonly used shortcuts to save coding time.

Order of Mathematical Operations

Order of Mathematical Operations

In this video, Doug Winnie reviews how Flash calculates math based on a specific order of operations.

Events and MouseEvent Handlers

Events and MouseEvent Handlers

Discover the power of events and how you can quickly and easily build event handlers. In this episode, Doug covers how to use events to build interactivity with the mouse.

Create a Timer

Create a Timer

Using your advanced knowledge of ActionScript, Doug Winnie walks you through on how to combine time events with event listeners to create and control time-based events.

Create a Clock

Create a Clock

See Doug build a clock in Flash using ActionScript to manipulate objects’ properties and add mouse and timer events. Everything you’ve learned from his tutorials is combined into one project.

Posted in Flash Tutorials1 Comment

Smart SWF Optimization with Custom Framerates

Smart SWF Optimization with Custom Framerates

Over the years, the Flash Player has received such a bad rep for hogging computer system resources even while displaying static content. There were many times in which I would wonder “What the heck is Flash processing?”. As for Flash Developers/Designers, there was only so much we can do to optimize the SWF via runtime. That was then, this is now! In Lee’s latest video tutorial, he demonstrates how you can dynamically change your movie’s framerate to use only the resources it needs.

With its introduction in AS3, you can dynamically change the framerate of your SWF movie. In an earlier tutorial, I demonstrated how you can change the framerate of your SWF and how it will effect a frame by frame animation.

By leveraging the ability to dynamically change the framerate of your SWF, it will allow you to take advantage of idle moments in your Flash applications by changing the the framerate based on the content being displayed. It’s a simple, yet great concept.

Check out Lee’s video, SWF Framerate Optimization, to learn more on how to implement such a concept. Enjoy!

Posted in Flash Tutorials2 Comments

Moving From AS2 to AS3: Creating Dynamic Masks

Moving From AS2 to AS3: Creating Dynamic Masks

Dynamic mask objects have been key to many Flash project’s success. When it comes to migrating over from AS2 to AS3, you’ll find that things have changed as the method “setMask()” in AS2 is now a property called “mask”. In this next edition of the Moving From AS2 to AS3 series, I will be comparing the two solutions and offering an efficient solution to creating dynamic masks using AS3.

Comparing AS2 to AS3

Setting masks dynamically using ActionScript 2.0

myMC.setMask(maskObject);

Setting masks dynamically using ActionScript 3.0

myMC.mask = maskObject;

So as you can see the syntax hasn’t changed much, however, personally I feel that AS3′s implementation is a bit more literal making it easier to understand.

Creating your masking objects as Sprites

While in ActionScript 2.0 there was no better of a solution than to create your masking object as a MovieClip. With the introduction of the Sprite object in ActionScript 3.0, creating your masking objects as Sprites is a far more efficient solution.

Since a mask object does not require a timeline, using a Sprite instead of a MovieClip simply makes more sense. Below is an example where a Sprite is used in place of a MovieClip:

// Create mask

var maskObject:Sprite = new Sprite();

maskObject.graphics.beginFill(0xFF0000);

maskObject.graphics.drawRoundRect(myMC.x, myMC.y, 453, 290, 20);

addChild(maskObject);

// Apply mask

myMC.mask = maskObject;

Download Example File

I hope this helps in your migration over into  AS3.  If there is something in particular you want to add or see with the Moving From AS2 to AS3 series, feel free to contact me via the contact page.

Posted in Flash Tutorials, Tutorials3 Comments

Moving From AS2 to AS3: Handling Depths

Moving From AS2 to AS3: Handling Depths

Managing depths in AS2 was pretty annoying and time consuming. You’d spend so much time dedicating depth ranges for MovieClip groups, but in the end the limitations of AS2 really got the last laugh. Who’s laughing now?

Improving upon handling depths

With the introduction of Flash Player 9 and ActionScript 3.0, Adobe created an easy and powerful way to add, remove, and change MovieClips on the screen. It’s is called the display list.

Understanding the Display List

Basically, the role of the display list is to handle managing where your MovieClips are placed in depth when visually adding them to the Flash stage. To learn more on this topic, the Yahoo Flash Developer has a thorough introduction article to understanding the display list.

What happened to swapDepths and getNextHighestDepth?

The swapDepths and getNextHighestDepth methods no longer exist in ActionScript 3.0. Instead you would rely using the DisplayObjectContainer methods associated with a MovieClip added to the display list.

Swapping depths using AS2

function arrangeBoxes():Void
{
for (var i:Number = 0; i < 3; i++)
{
//Attaching the MC from th library for the duration of the loop
var box:MovieClip = this.attachMovie("box", "box" + i + "_mc", this.getNextHighestDepth(), {_x: ((i * 80) + 100), _y: 100});
var boxColor:Color = new Color(box);
boxColor.setRGB(Math.random() * 0xFFFFFF);
box.onRollOver = function():Void
{
//Focused box will achieve to the next highest depth
this.swapDepths(this._parent.getNextHighestDepth());
}
}
}
arrangeBoxes();


If you noticed in the AS2 solution, we are basically making the interacted object obtain the next highest depth available on the stage. Sounds correct and automated but there is nothing really stopping this from reaching a depth of 9999 with only 3 objects on stage. Basically, this is no where near an efficient solution to depth swapping.

Swapping depths using AS3

function arrangeBoxes():void
{
//For loop will create and place three boxes onto the stage
for (var i:int = 0; i < 3; i++)
{
var boxColor:ColorTransform = new ColorTransform();
boxColor.color = (Math.random() * 0xFFFFFF);
//Define a new box to be added to the stage
var box:Box = new Box();
box.x = ((i * 80) + box.width);
box.y = 100;
box.transform.colorTransform = boxColor;
box.buttonMode = true;
box.addEventListener(MouseEvent.MOUSE_OVER, swapMyDepth);
this.addChild(box);
}
}

function swapMyDepth(evt:MouseEvent):void
{
this.setChildIndex(Box(evt.target), (this.numChildren – 1));
}

arrangeBoxes();


I am just amazed at how much easier and efficient the swapping depth syntax appears in AS3. In the case of ActionScript 3.0, this solution literally swaps the depth of targeted objects. There is no “false advertising” of swapping depths.

Overall, there is very little left for the designer/developer to manage when dealing with object depth. One less headache to deal with. Phewww!

Download source

Feedback:

I hope this helps in your migration over into  AS3.  If there is something in particular you want to add or see with the Moving From AS2 to AS3 series, feel free to contact me via the contact page.

Posted in Flash Tutorials, Tutorials2 Comments

Playing, Stopping, and Pausing Sounds Using AS3

Playing, Stopping, and Pausing Sounds Using AS3

In a previous tutorial, I demonstrated a simple solution to loading an external sound file. In that example, the mp3 file that had been loaded begins to play automatically. While this might be fine in some cases, you probably would want more control over the sound being imported.

For example, being able to stop or pause then play again might be a good place to start.   In this tutorial, I will be demonstrating how to play, stop, and pause sounds using AS3 once you have the sound loaded into Flash.

Playing a sound

Playing a sound using AS3 is a simple as calling the play() method of the defined sound object. Previously in AS2, you would have called the start() method so not much different in this area.

soundClip.play();

Stopping a sound

Stopping a sound using AS3 is accomplished by calling the stop() method of the defined sound object. This is exactly the same way you would be able to handle it using AS2.

soundClip.stop();

Pausing a sound

This is where pausing a sound using AS3 is quite different from using AS2. As it stands now, there is no method to automatically pause a sound using AS3. Instead, you must populate an optional parameter of the play() method.

It allows you to play the sound using an offset value that is passed in from a stored variable. Below is an example of accomplishing this.

//Stores the position of the "playback head"
var pausePosition:Number = sndChannel.position;
sndChannel.stop();

//When ready to resume playback, call this line
sndChannel = soundClip.play(pausePosition);

Putting it all together

Pause/Play SoundNow it is time to integrate all three.  I have provided an example that puts all three of these control functionalities into good use.  The example is sessentially a simple music player with toggle functionality.

Preview example

Download source

Subscribe to the RSS Feed to stay updated on future tutorials on using sound in AS3.

I hope this helps in your migration over into  AS3.  If there is something in particular you want to add or see with the Moving From AS2 to AS3 series, feel free to contact me via the contact page.

Posted in Flash Tutorials, Tutorials7 Comments

Filtering XML Data Using AS3

Filtering XML Data Using AS3

Filtering data XML data using AS2 has to be one of the most sought out features when dealing with XML-driven Flash projects. Being able to automatically grab certain relevant information without manually searching each and every XML node and/or attribute.

What if we were given the ability to create filters that will automatically pull the information needed from XML nodes and/or attributes. But wait we can’t do that, right? Right, that is until the birth of ActionScript 3.0.

Another new feature in AS3 is the ability to filter and display only the data you are interested in. With this, you can dynamically filter XML nodes and attributes.

Filtering XML Node Values

Let’s say you wanted to pull all the of the books that were paperback. You can now create a function that scans each XML’s node or attribute value and returns which node would qualify with the given query. See the example below in which outputs the books in which are paperback.

Note: I am using this XML file in the example.

var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();
//Adding an event listener to notify when loading is completed
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
//Load the XML file
xmlLoader.load(new URLRequest("book-list.xml"));

function LoadXML(e:Event):void {
xmlData=new XML(e.target.data);
ParseBooks(xmlData);
}

function ParseBooks(bookInput:XML):void {
//Creating an xml list that will store the book info
var books:XMLList=bookInput.book.children();
//Creating a xml list that will store the book's ISBN number
var bookAttributes:XMLList=bookInput.book.attributes();
//Filter out all of the books with a "Paperback" cover
var  paperBackList:XMLList  =  bookInput.book.(coverType == "Paperback");
trace(paperBackList);
}

Filtering XML Attributes

Not only can you filter XML node values but you can do the same to XML Attributes values. In the a previous post , Loading XML Data, I created and included an attribute labeled “ISBN” which would be available within each book node. If you wanted to return a list of books that matched a certain value, it would go something like this.

Note: I am simply replacing the ParseBooks function from the code above

function ParseBooks(bookInput:XML):void {
//Creating an xml list that will store the book info
var books:XMLList=bookInput.book.children();
//Creating a xml list that will store the book's ISBN number
var bookAttributes:XMLList=bookInput.book.attributes();
//Filter out the book with a matching ISBN number
var  closeMatchList:XMLList  =  bookInput.book.(@isbn == "978-0596526948");
trace(closeMatchList);
}

As you can see, there isn’t much of a difference with filtering by XML node values or attribute information. Filtering can provide such a dynamic form of functionality to any Flash project: big or small.

Download Source

I’d love to hear from you.  What do you think of this new functionality when dealing with XML data?

Feedback:

I hope this helps in your migration over into  AS3.  If there is something in particular you want to add or see with the Moving From AS2 to AS3 series, feel free to contact me via the contact page.

Subscribe to the RSS Feed to stay updated on future tutorials on using XML in AS3.

Posted in Flash Tutorials, Tutorials6 Comments

Loading External Sounds Using AS3

Loading External Sounds Using AS3

Sound has become a key addition to many Flash projects: offline and online. In many cases, integrating sound can actually amplify the final results of a project. However, in many other cases sound should not even be a topic for discussion.

Loading external sound into your Flash projects using AS2 is a fairly easy task.  Using AS3 to load external sounds is just as simple.  I am going to quickly go over how to load an external sound file using AS3 in comparison to AS2 syntax.

Loading external sound using AS2

//Create a new sound object
var song:Sound=new Sound();
//Load the external sound file
song.loadSound("song.mp3",true);
//Once loaded play the sopund file
song.onSoundComplete=function() {
	song.start();
}

Loading external sound using AS3

//Create an instance of the Sound class
var soundClip:Sound=new Sound();
//Create a new SoundChannel Object
var sndChannel:SoundChannel=new SoundChannel();
//Load sound using URLRequest
soundClip.load(new URLRequest("song.mp3"));
//Create an event listener that wll update once sound has finished loading
soundClip.addEventListener(Event.COMPLETE,onComplete,false,0,true);
function onComplete(evt:Event):void {
	//Play loaded sound
	sndChannel=soundClip.play();
}

What is the difference?

Event model consistency

Loading external sound and playing it using AS3 is quite similar to that of AS2 syntax. The key difference between the two would have to the new event model integration that AS3 brings to the table.

Introducing Sound Channel

One other difference is the declaration and use of a Sound Channel. The SoundChannel class is used to create a separate channel for each new sound played. By placing each sound in its own channel, you can work with multiple sounds but control each sound separately.

Conclusion

Overall, the changes between AS2 to AS3 in loading external sound are not far off from each other. However, AS3 does introduce a boat load of new features and classes that allow for creative uses of sound in your Flash Projects. Some of the other new features include: visualizing sound data, reading ID3 Metadata, and transformation of the sound files.

Download Source

Subscribe to the RSS Feed to stay updated on future tutorials on using sound in AS3.

I hope this helps in your migration over into  AS3.  If there is something in particular you want to add or see with the Moving From AS2 to AS3 series, feel free to contact me via the contact page.

Posted in Flash Tutorials7 Comments

Loading XML Data Using AS3

Loading XML Data Using AS3

Thanks to the Adobe Gods for making the lives of so many Flash developers much less complicated when dealing with XML Data. XML and AS2 just did not get along very well. It was one of those situations where there was a love/hate relationship.

Love was there when you’ve hacked yourself an impressive solution that simple works well, but that hate returns when it was time to change the XML structure. Going back and rerouting the paths to the correct XML nodes was just painful.

It’s funny because I did not foresee a brighter day for dealing with Flash and XML data. Those brighter days have now finally come with the newly added XML classes that will basically do all the work for you.

The XML libraries have been completely overhauled in AS3. These new changes provide a much more seamless XML integration that is based on the web standards of E4X.

What is E4X?

E4X (ECMA for XML) is the current World Wide Web Consortium standard for reading and writing XML documents, and greatly reduces the amount of code and hoop-jumping required to communicate with XML. It allows you to treat XML objects like any other object with familiar dot syntax, and provides additional shortcuts for traversing XML trees.

By providing the support for E4X, the amount of code and maneuvering in and out of XML nodes is greatly reduced and easier to understand.

In the examples below, I will first demonstrate the AS2 integration of loading XML data followed by the AS3 comparison.

Loading XML data using AS2

//Load XML Data
function loadXML(loaded) {
	if (loaded) {
		var xmlNode=this.firstChild;
		var total:Number=xmlNode.childNodes.length;
		//Creating the arrays needed for storing off the XML data
		var bookInfo:Array=new Array(total);
		var isbnNum:Array=new Array(total);
		var subNum:Array=new Array(total);
		for (var i:Number=0; i<total; i++) {
			//Storing off the ISBN values into an array
			isbnNum[i]=xmlNode.childNodes[i].attributes.isbn;
			//Storing off each parent's(book) children count
			subNum[i]=xmlNode.childNodes[i].childNodes.length;
			bookInfo[i]=new Array(subNum[i]);
			trace("ISBN = "+isbnNum[i]);
			trace("Book Info:");
			for (var j:Number=0; j<subNum[i]; j++) {
				//Store the book info of all the books into a 2D Array
				//Thie is the path to the desired xml nodes
				bookInfo[i][j]=xmlNode.childNodes[i].childNodes[j].firstChild.nodeValue;
				trace(bookInfo[i][j]);
			}
		}
	} else {
		trace("Error loading XML");
	}
}
//Required syntax
xmlData=new XML  ;
xmlData.ignoreWhite=true;
xmlData.onLoad=loadXML;
xmlData.load("book-list.xml");
stop();

Loading XML data using AS3

var xmlLoader:URLLoader=new URLLoader  ;
var xmlData:XML=new XML  ;
//Adding an event listener to notify when loading is completed
xmlLoader.addEventListener(Event.COMPLETE,LoadXML);
//Load the XML file
xmlLoader.load(new URLRequest("book-list.xml"));

function LoadXML(e:Event):void {
	xmlData=new XML(e.target.data);
	ParseBooks(xmlData);
}

function ParseBooks(bookInput:XML):void {
	//Creating an xml list that will store the book info
	var books:XMLList=bookInput.book.children();
	//Creating a xml list that will store the book's ISBN number
	var bookAttributes:XMLList=bookInput.book.attributes();
	//Extract the data from the populated XML lists
	for (var j:int=0; j<bookAttributes.length(); j++) {
		var bookISBNNum:XML=bookAttributes[i];
		trace("ISBN = "+bookISBNNum);
	}
	for (var i:int=0; i<books.length(); i++) {
		var bookInfo:XML=books[i];
		trace(bookInfo);
	}
}

What’s the difference?

The Use of XML Lists

A XML List is a list use to store specific XML nodes or attributes. The way I see it XML Lists are basically arrays formatted for dealing with XML data. This eliminates the need of creating all multiple arrays to store your data for further use – the XML List will do it all for you. If we wanted to, we can save off the an individual list for the author and book title by simply creating an XML List and filtering the specific node data. See code below.

Returning any or all of the XML data

Filtering and storing off any or all XML data becomes a more natural process.

//This xml list stores all of each book's data
var bookChildren:XMLList = bookInput.Book.children();
//This xml list will only store the author's info
var authorList:XMLList=bookInput.book.author;
//This xml list will only store the title's info
var titleList:XMLList=bookInput.book.title;

No need to define ignoreWhite to true

WithinAS3 there is not a need to define the ignoreWhite state to true. By default this is automatically set to true. Makes sense right!

Overall, you can see that loading XML data into Flash is as seamless as can be. No more headaches on trying to get your XML file to work for you. There’s more to the new XML classes than what you see on this page and I plan to touch on more of it in the next few days. If you are in need of additional resources, check out the ones below.

Additional Resources:

Download Source

I hope this helps in your migration over into  AS3.  If there is something in particular you want to add or see with the Moving From AS2 to AS3 series, feel free to contact me via the contact page.

Posted in Flash Tutorials1 Comment

Page 1 of 41234