PDA

View Full Version : Waiting untill loaded


guywald
05-30-2008, 02:08 PM
Hi,

I am loading a XML text file in to a variable:

var TreeData:XML = new XML;
var xmlString:URLRequest = new URLRequest("TreeData.xml");
var xmlLoader:URLLoader = new URLLoader(xmlString);
xmlLoader.addEventListener(ProgressEvent.PROGRESS, showProg);
xmlLoader.addEventListener(Event.COMPLETE,initData );

function showProg(evt:Event):void {
trace("In Prog");
}

function initData(evt:Event):void {
trace("TreeData XML Load complete");
TreeData = XML(xmlLoader.data);
trace("TreeData trace = "+TreeData.toXMLString());
//var numOfCategories:Number = TreeData.Category.length();
//var CategoryArrays:Array = new Array(numOfCategories);
}


After this code I have some code that uses the XML data.
How do I make the program pause untill the XML file has loaded in to the variable and just then continuing with all the rest?
:confused:


Thanks,
Guy

box86rowh
05-30-2008, 02:13 PM
Looks like you have it...just need your xmlLoader.load() after you add the onComplete eventHandler..

guywald
05-30-2008, 02:29 PM
It runs the rest of my program before it loads the XML to the var.

guywald
05-30-2008, 02:31 PM
var TreeData:XML = new XML;
var xmlString:URLRequest = new URLRequest("TreeData.xml");
var xmlLoader:URLLoader = new URLLoader(xmlString);
xmlLoader.addEventListener(ProgressEvent.PROGRESS, showProg);
xmlLoader.addEventListener(Event.COMPLETE,initData );
xmlLoader.load(xmlString);


function showProg(evt:Event):void {
trace("In Prog");
}

function initData(evt:Event):void {
trace("TreeData XML Load complete");
TreeData = XML(xmlLoader.data);
trace("TreeData trace = "+TreeData.toXMLString());
//var numOfCategories:Number = TreeData.Category.length();
//var CategoryArrays:Array = new Array(numOfCategories);
}

var MainCat2:Array = new Array;
trace("TreeData trace 2 = "+TreeData.toXMLString());


If I go step by step,
it reaches the line "xmlLoader.load(xmlString);"
and jumps to :
var MainCat2:Array = new Array;
trace("TreeData trace 2 = "+TreeData.toXMLString());

so I can see that TreeData trace 2 is empty

spooner
05-30-2008, 03:21 PM
That is because it loads asynchonously with your code. The load function does not pause and wait for your XML to load, it fires off an http request and then carries on. You then do your trace("TreeData trace 2 = ... etc) and the XML is still in the process of loading from the server... then, at a later point it finishes the http request, loads the xml, and then fires initData(), where it correctly sets the TreeData.

If your code requires info from the xml, then you need to make that code be fired explicitely after the initData function is called, in other words call another function from initData, to do trace 2

guywald
05-30-2008, 05:58 PM
Hooray! It works great!!! ;);)