Hi there,
I am a real newbie at actionscript and have been playing around with it and trying to learn from examples for the last couple of days. I finally thought I was starting to get a handle on things but I am still having trouble…
What I want to do is read in an xml file once, and store the info from it in global variables so that I can just call each tidbit at different points along the way. I found some code for global variables at http://www.uza.lt/codex/as3-global-object/ and tested it out and was able to make that work. I also figured out how to load XML data and tested that in another file. But when I come to combine the 2 parts, I run into trouble …
So here’s what I have so far, an external class file called dyr.as which has the following code:
package {
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.text.TextField;
import lt.uza.utils.*;
public class dyr extends MovieClip
{
// initialize the global object
// you have to repeat this step in every class that will use the global
private var global:Global = Global.getInstance();
// set loader var
private var loader:URLLoader = new URLLoader();
// set xml var
private var xml:XML;
public function dyr() {
loader.addEventListener(Event.COMPLETE, onLoaded);
loader.load(new URLRequest("http://members.iinet.net.au/~christine/suburbs.xml"));
global.testVar = "This is a test";
}
// FUNCTIONS
public function onLoaded(e:Event):void
{
xml = new XML(e.target.data);
var subList:XMLList = xml.suburbData;
var suburbNum:uint = randRange(1,subList.length())-1;
global.subName = subList.suburbName.text()[suburbNum];
global.header1 = subList.header1.text()[suburbNum];
global.fact1 = subList.fact1.text()[suburbNum];
global.header2 = subList.header2.text()[suburbNum];
global.fact2 = subList.fact2.text()[suburbNum];
global.header3 = subList.header3.text()[suburbNum];
global.fact3 = subList.fact3.text()[suburbNum];
trace(global.subName);
trace(global.header1);
trace(global.fact1);
trace(global.header2);
trace(global.fact2);
trace(global.header3);
trace(global.fact3);
}
public function randRange(low:Number, high:Number) : Number
{
return Math.floor(Math.random() * (1+high-low)) + low;
}
}
}
And then I have my fla where I try to set a local var to my global var to then use in a dynamic text field…
trace(global.testVar);
trace(global.subName);
suburb_txt = global.subName;
trace(suburb_txt);
Then my output shows the following:
This is a test
undefined
null
Fremantle
Local Schools
Fremantle Primary School
Price Growth
34%
Median House Price
$800,000
So basically the global var works, and the xml loads, but the text field seems to get set before the xml is loaded?? Any idea how I get around that… And also any pointers or tips on whether I am on the right track or if there is a simpler way to achieve what I want would be appreciated!!
Cheers
Christine