private var xmlLoader:URLLoader;public function LoaderClass { var URL:String = xmlFile; if Capabilities.playerType != "External" && Capabilities.playerType != "Standalone"{ URL += "?" +
Trang 1Chapter 17: XMLDocument, XMLNode, XML, and XMLList Classes 253
* XML.ignoreWhitespace = true
* XML.prettyIndent = 2
* XML.prettyPrinting = true
Example (file 1)XML.ignoreComments = false;
XML.ignoreProcessingInstructions = false;
var customSettings:Object = XML.settings();
/******** will override the previous settings
************************/
XML.setSettings(XML.ignoreComments = true);
XML.setSettings(XML.ignoreProcessingInstructions = true);var xmlData:XML = XML(event.target.data);
<built description="Built in">1982</built>
<city description="City:">North Sacramento</city>
Retrieves the following properties: ignoreComments, ignoreProcessingInstructions, ignoreWhitespace,prettyIndent, and prettyPrinting
Example (file 2)Script in InitiateXml_ss.as:
XML.ignoreComments = false;
XML.ignoreProcessingInstructions = false;
var customSettings:Object = XML.settings();
/******** will override the previous settings
************************/
XML.setSettings(XML.ignoreComments = true);
Trang 2XML.setSettings(XML.ignoreProcessingInstructions = true);//or for all settings:
<built description="Built in">1982</built>
<city description="City:">North Sacramento</city>
Trang 3Chapter 17: XMLDocument, XMLNode, XML, and XMLList Classes 255
Returns the XML object as a string The rules for this conversion depend on whether the XMLobject has simple content or complex content If the XML object has simple content, the start tag,attributes, namespace declarations, and end tag are eliminated If the XML object has complexcontent, the whole XML object with all tags is returned To return the entire XML object everytime, the toXMLString( ) method is used
Example (file 3)var xmlData:XML = XML(event.target.data);
<hs:Built text="Built in ">1990</hs:Built>
<hs:Location text="Located in ">Sacramento</hs:Location>
<hs:Price text="Price: ">$239,000</hs:Price>
</hs:Body>
</hs:Agency>
Simple:
toXMLString() methodtoXMLString():String
Returns the XML object as a string The toXMLString( ) method always returns the start tag,attributes, and end tag of the XML object, regardless of whether the XML object has simple con-tent or complex content
Example (file 3)var xmlData:XML = XML(event.target.data);
Trang 4<hs:Location text="Located in ">Sacramento</hs:Location>
<hs:Price text="Price: ">$239,000</hs:Price>
The XMLList Class
An XMLList object is an ordered collection of properties An XMLList object represents an XMLdocument, an XML fragment, or an arbitrary collection of XML objects An XMLList object withone XML element is treated the same as an XML object When there is one XML element, allmethods that are available for the XML object are also available for the XMLList object
XMLList(value:Object)
Creates a new XMLList object
The following methods are similar to those from the XML class Check the XMLList folder forexamples and definitions
An example for the attribute method is given here
Trang 5Chapter 17: XMLDocument, XMLNode, XML, and XMLList Classes 257
it an XMLList object we would get the following error message, because the length of the object
is more than 1:
Implicit coercion of a value of type XML to an unrelated type XMLList
var data:XML = InitiateXml.xData;
var xmlFragment:XMLList = data.house;
trace(xmlFragment.attribute("id"));
Trace is
1 1
Methods of the XMLList class
attributes():XMLListchild(propertyName:Object):XMLListchildren():XMLList
comments():XMLListcontains(value:XML):Booleancopy():XMLList
descendants(name:Object = *):XMLListelements(name:Object = *):XMLListhasComplexContent():Boolean
hasOwnProperty(p:String):BooleanhasSimpleContent():Boolean
isPrototypeOf(theClass:Object):Booleanlength():int
normalize():XMLListparent():ObjectprocessingInstructions(name:String = "*"):XMLListpropertyIsEnumerable(p:String):Boolean
setPropertyIsEnumerable(name:String, isEnum:Boolean = true):void
text():XMLListtoString():StringtoXMLString():StringvalueOf():XMLList
The LoaderClass Class
As the exercise of this chapter, we will create the LoaderClass class, which we have used so far forall the examples This class not only is the AS2 homologous class that we have created for loading
Trang 6XML files for Flash 8, but also includes the capabilities to load images and movies We will designthis class to be able
● to load images and movies,
● to load XML files from a foreign server using the proxy method,
● show XML data that will be available in XMLDocument and XML class format, and
● to show XML files that will not stay in cache and to be renewed every time the file is loaded
If you do not want the last option, you can easily alter the file We have used this class for this chapterand will use it in the following chapters In this exercise we discuss only the XML loading capabilities
At a later stage, when we need the class to load images, we will discuss the function that loads images
We start the script by importing several classes We place the script in a folder named “Helper”,which means that we need to define the path as package scripts.helper
package scripts.helper{
We could import classes using a wildcard (∗), but in this base class we try to avoid that, to have only
the classes that we need available
We declare several variables, but only “xmlLoader” is important for loading XML files
private var urlLoader:Loader;
private var holder:MovieClip;
private var im_url:String;
Flash XML Applications
258
Trang 7private var xmlLoader:URLLoader;
public function LoaderClass (){
var URL:String = xmlFile;
if (Capabilities.playerType != "External" &&
Capabilities.playerType != "Standalone"){
URL += "?" + new Date ().getTime () + Math.floor (Math.random () * 10000);
}
We now use two classes to load the XML file; the first is the URLRequest class, which capturesinformation of an http request and passes it on to the load method, in this case of the URLLoaderclass The second class is the URLLoader class, which downloads data from a URL This class is suitable for text We create a new instance of the URLLoader class and let it invoke several event listeners This is similar to the former load/onLoad event handling, as we know it from AS2
var request:URLRequest = new URLRequest(URL);
xmlLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, loadParse);xmlLoader.addEventListener(IOErrorEvent.IO_ERROR, ifFailed);
xmlLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
We then use the URLRequest Method class, which specifies whether a URL should use the
“POST” or the “GET” method Although this is not required for loading XML files directly from
Chapter 17: XMLDocument, XMLNode, XML, and XMLList Classes 259
Trang 8the local server, it is required if we want to load XML files via the PHP-proxy method We thenuse the URLLoader load method, which will result in a response from the server.
request.method = URLRequestMethod.POST;
urlLoader.load(urlRequest);
}
If loading has a problem, the user will be notified:
private function ifFailed (event:IOErrorEvent):void{
trace("Status is " + event.status);
}}}
Both of the above classes are shared by the two main public functions We will use this class fromnow on, whenever we load an XML file or an image or movie For demonstration purposes we testthis class calling an XML file from a foreign domain using the proxy method
Testing the LoaderClass Class
We already extensively tested the LoaderClass class when we went through the methods and erties of the different XML-related classes As the final test we check if the class also works when
prop-we call an XML file from a foreign domain To execute this prop-we create the Proxytest class, which
is similar to the XML-related classes except that we replace the trace actions by a TextField Weplace this script in the fla file, which will create a new instance of the Proxytest class, and call itmyProxy.php In the Document class text field we add the path to the Root class to create a timeline:
var URL:String = "myProxy.php";
var a:Proxytest = new Proxytest ();
a.parseData (URL);
The Proxytest class has the following executing script We start with the variable declarations
We create a “LoaderClass” variable and a “Root” variable, which will be the timeline in the movie.private var pXml:LoaderClass;
private var _root:MovieClip = Root._root;
Flash XML Applications
260
Trang 9Chapter 17: XMLDocument, XMLNode, XML, and XMLList Classes 261
Then we load the XML file by creating a new LoaderClass instance and executing the “initXML”function
public function parseData (xmlFile:String):void{
pXml = new LoaderClass ();
pXml.initXML (xmlFile, loadParse);
}
Once the XML file is loaded the “loadParse” function is executed and we retrieve the XML data,
as we are used to doing Then we create a TextField instance, which we add to the _root timeline:
private function loadParse (event:Event):void{
var xmlData:XML = XML(event.target.data);
var showXML:TextField = new TextField ();
Trang 1018 Menu Bar and ComboBox
Overview
In this chapter we will create the first application using ActionScript 3 We will develop a menu barthat is similar to the one we created before (Chapter 12) However, instead of using the former AS2script we will script this menu bar from the beginning There will be particular focus on changesfrom AS2 to AS3 and these will be explained in detail The second object we will develop is aComboBox-type menu I did not have access to any components when this book was written
The Menu Bar: fla
Before we start writing any scripts we need to design the parts that we need for the menu bar.Actually, we can take all the MovieClips from the former menu bar, which was called
“custom_menubar” We can take the fla file and use it again for the new menu bar However, weneed to make some changes First of all we change the Publish-Settings to Flash 9 —ActionScript
3 This will cause a dramatic change in the movie that is very different from a change from Flash 7
to Flash 8 Open the fla file custom_menubar_AS2.fla in the Chapter 18 —Menubar —Menubar_Starter folder and make those Publish-Settings changes Now open the library and click
on one of the MovieClips and check the properties All the linkage information is gone and instead
in the class slot there is the former class path written, and in the Flash 9 preview it says generated”, while in Flash CS3 it will show only the class name Therefore, the first task will be
“Auto-to write a simple base class for all MovieClips except for the frame MovieClip (see the MenuBarclass as an example) We then go back to the MovieClips in the library and enter the class path foreach MovieClip We also delete all former AS2 ActionScript from the movie
In this movie we are using frames and, as I mentioned earlier, it might be a better strategy to define
a timeline with a name to which we can always refer, despite the fact that Flash will automaticallycreate one Therefore, we write a root class for the timeline, which is our Document class
package scripts.menubar{
import flash.display.MovieClip;
public class Root extends MovieClip
262
Trang 11{public static var _root:MovieClip;
public function Root (){
_root = this;
}}}
We can now place any object on this timeline and if we need to refer to an object from a differentclass we use the name of the timeline (_root) and the name of the object
The Menu Bar: XML
Before we write any code we need to design the XML file Since we use AS3 we will make use ofthe new XML class, which facilitates parsing XML However, we also have to be careful now innaming each node if we do not want to miss any When we used the XMLDocument class (formerXML class) we were searching for child nodes and all node names could be different We can still
do that with methods from the new XML class, but there is also an even easier way, by just callingthe node name To make use of this option we give common nodes the same node names If youlook at the XML file that we use for the menu bar you will see:
Trang 12We give all nodes the name item Then later we can loop through the XML file by using
“XML.item(count).Data” in case we want to catch all the Data nodes We then do not have toworry that any of the child nodes might not be wanted, which could happen if we ask for all childnodes As you can see here we no longer use as many attributes as we often used in XML files thatwere parsed using AS2 Attributes were easier to use then We are now ready to write code
The Menu Bar: Myparser.as
In the following scripts the classes to import and the class variables will no longer be mentioned.They are listed in the Starter scripts The imported classes are always divided into Flash classes andcustom classes, which we create When you see a wildcard (.*), it means that more than one class
of that path will be imported We extend the Sprite class for this class, since there are no frames and
we do not add any non-class-declared properties
We have to decide, at this point, how we will proceed There are different ways to place an object.One possibility is to create a MovieClip as a container and place all objects that belong to the appli-cation into the MovieClip We will do that for the ComboBox (see below) For the menu bar weuse a different strategy We use the MenuBar object, which is the background bar for the menu, asthe orientation for all other objects In the class script, which has code to place the MenuBar on
the timeline, we add the x and y coordinates The name of this class is Myparser We place the code
for the coordinates in the constructor for that class and use new static variables for the values Wealso define the timeline variable “_root” here
public function Myparser (xpos:uint, ypos:uint){
Trang 13The next task will be to call the XML file, and using a public function, which will be initiated in the.fla file, does this From now on we use a new class, the LoaderClass, which contains the main functionfrom the InitiateXml class, in a modified form, and, additionally, a function to load images and movies.
public function parseData (xmlFile:String):void{
private function loadParse (event:Event):void{
var xmlData:XML = XML(event.target.data);
We first add the MenuBar object and position it with the x and y coordinates, which we got from the movie We place it on “_root” Unlike in AS2, x and y and other variables do not have any underscore.
var menuBack:MenuBar = new MenuBar();
var bLength:MenuButton = new MenuButton();
menuBack.width = xmlData.children().length() * bLength.width;
menuBack.x = xposition;
menuBack.y = yposition;
_root.addChild(menuBack);
Now we loop through the XML data to get all children As you can see we access the node values
by directly calling the nodes with the node name item Please note also that length( ) is amethod and not a property, unlike in arrays
for (var count01:uint = 0; count01 <
xmlData.children().length(); count01++){
var linkData:String = xmlData.item[count01].Links;var mName:String = xmlData.item[count01].Name;var mData:String = xmlData.item[count01].Data;
We create Button instances for each item node:
var button:MenuButton = new MenuButton();
We use a setter to associate the strings encoded in the variables to the buttons Later, when wewrite the code for the MenuButton, we will need to add a setter( ) method
Chapter 18: Menu Bar and ComboBox 265
Trang 14We arrange the buttons using the original x and y coordinates and the width of each button:
button.x = xposition + button.width*count01;
button.y = yposition;
This is the end of the first class We need to add a script to the fla file in frame 1, where we create
an instance of this class
by yourself or use the Myparser_ready.as file, but convert the name to Myparser.as
Flash XML Applications
266
Trang 15The Menu Bar: MenuButton Class
Now that we have the menu bar and menu buttons we need to give function to the buttons Thereare two types of buttons, one for moving the timeline from one frame to another and one to open
a menu with links But before we get into the details of that, we need to add some general ods to all of the buttons Instead of using onPress or onRelease for button functions, as we wereused to from AS2, we add event listeners This should also be familiar to you from the Flash 8 com-ponents, but it may be unfamiliar for you to use them for simple MovieClips or buttons We addthe event listeners to the constructor We create three listeners for different mouse events We alsodefine the timeline variable “_root” in this class and at a later point we’ll need an array We createthe Array instance here We add several mouse events, such as MOUSE_OVER, MOUSE_OUT,and MOUSE_DOWN, which add button behavior
meth-public function MenuButton (){
_root = Root._root;
indexArray = new Array ();
addEventListener (MouseEvent.MOUSE_OUT,mouseOutHandler);
addEventListener (MouseEvent.MOUSE_OVER, mouseOverHandler);
addEventListener (MouseEvent.MOUSE_DOWN, mouseDownHandler);
As you may remember, in the Myparser class we added a setter to the menu buttons We now add the setter method mData is the frame name, while lData is the nodes with the nodenameLinks
public function set dataSet(myData:String):void{
mData = myData;
}public function set linkSet(liData:String):void{
Trang 16private function mouseOverHandler(event:MouseEvent):void
{event.target.gotoAndPlay("frame2");
}The mouse-down function is the main function for the buttons We prepare to close the linksdrop-down menu when it is open This is triggered when any of the other buttons is pressed Thesign that a drop-down menu is open is when the indexArray length is larger than 0
private function mouseDownHandler(event:MouseEvent):void
{if(indexArray.length > 0){
By using a “for” loop and the number of links as limit we remove all the previous dropped downlinks
for (var count02 = 0; count02 <
linkData.children().length(); count02++){
is given by the expression “linkData.children( ).length( )” Allitem nodes that lack
aLinks node will have 0 children, while those with a Links node will have more than 0children Therefore, nodes with a linkLength of 0 have aData node with a frame name as thenode value In this way we can easily add as many links as we like and wherever we want and themenu is completely autonomous and will be determined by the XML alone
linkData = XMLList(lData);
var linkLength:int = linkData.children().length();if(linkLength == 0)
{_root.gotoAndStop(mData);
}else{
Flash XML Applications
268