Heres'a very basic set of classes that use an internal xml object (for clarity and simplicity; the downstream processes are the same for external XML)
The Btn class illustrates the use of setters and getters to assign and retrieve private instance properties as well as executing other code while doing so. (such as assigning a string to the textfield.text, resizing the button shape to fit the text, and repositioning the textfield.)
The links are assigned to an instance property of the button class, then retrieved in the click handler.
>
Create a new empty AS3 FLA; save to a folder on the desktop.
Paste the following code blocks into new AS3 class files, named as shown, and save them to the same directory as the FLA.
Set the Document class of the FLA to Main.
Compile the SWF.
Main.as
ActionScript Code:
package
{
import flash.display.*;
import flash.events.*;
public class Main extends Sprite
{
private var xml:XML;
private var menu:Sprite;
public function Main()
{
xml =
<site>
<item title="Home" link="home.swf"/>
<item title="About us" link="about.swf"/>
<item title="Portfolio" link="porfolio.swf"/>
<item title="Contact Us" link="contact.swf"/>
<item title="Gallery" link="gallery.swf"/>
</site>
menu = new Sprite();
var pad:Number = 2;
var bY:Number = 0;
for each (var itm in xml.item)
{
var b:Btn = new Btn();
b.link = itm.@link;
b.label = itm.@title;
b.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
b.x = 0;
b.y = bY;
menu.addChild(b);
bY = menu.height + pad;
}
addChild(menu);
}
private function onClick(e:MouseEvent):void
{
trace(e.target.link);
}
}
}
Btn.as
ActionScript Code:
package
{
import flash.display.*;
import flash.events.*;
import flash.text.*;
public class Btn extends Sprite
{
private var _link:String;
private var _label:String;
private var btnLabel:TextField;
private var btnBase:Shape;
private var labelText:String;
public function Btn()
{
btnBase = new Shape();
var g:Graphics = btnBase.graphics;
g.beginFill(0xEEEEEE);
g.drawRect(0,0,120,30);
g.endFill();
addChild(btnBase);
btnLabel = new TextField();
btnLabel.autoSize = TextFieldAutoSize.LEFT;
this.label = "default";
addChild(btnLabel);
mouseChildren = false;
buttonMode = true;
addEventListener(MouseEvent.ROLL_OVER, onOver, false, 0, true);
addEventListener(MouseEvent.ROLL_OUT, onOut, false, 0, true);
}
private function onOver(e:MouseEvent):void
{
labelText = _label;
this.label = "Click this button to trace its link!"
btnBase.alpha = .5
}
private function onOut(e:MouseEvent):void
{
this.label = labelText;
btnBase.alpha = 1;
}
public function set link(value:String):void
{
_link = value;
}
public function get link():String
{
return _link;
}
public function set label(value:String):void
{
_label = value;
btnLabel.text = _label;
btnBase.width = btnLabel.width + 20;
btnBase.height = btnLabel.height + 20;
btnLabel.x = btnBase.width/2 - btnLabel.width/2;
btnLabel.y = btnBase.height/2 - btnLabel.height/2;
}
public function get label():String
{
return _label;
}
}
}