user1203605
user1203605

Reputation: 83

AS3 Using variable from one function in another - not working

Can't seem to get the value of myXML outside the function, despite being declared outside. What am I missing here? The data loads and traces correctly inside the function.

var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("flightPlannerBoard.xml"));

var myXML:XML;

// Check XML data fully loaded
myLoader.addEventListener(Event.COMPLETE, processXML);

function processXML(e:Event):void {

myXML = new XML(e.target.data);
//trace(myXML);
}
trace(myXML);

Upvotes: 0

Views: 1780

Answers (3)

shanethehat
shanethehat

Reputation: 15570

Because ActionScript is asyncronous as others have said, you cannot control the flow of execution by code placement. What you must do is control execution through the events, and so whatever actions you want to perform with the loaded XML should be in the processXML function or in another function that is called from processXML:

var myXML:XML;

function processXML(e:Event):void {
    myXML = new XML(e.target.data);
    trace(myXML);  //this trace will work
    doNextAction();
}

function doNextAction():void {
    trace(myXML);  //this trace will also work
}

Upvotes: 1

Jonatan Hedborg
Jonatan Hedborg

Reputation: 4432

Actionscript is an asynchronous language, meaning the trace "outside" the callback will be called before the file has loaded. The execution order in your case is:

  1. create instance of URLLoader
  2. start loading file
  3. add event listener to listen to the complete event
  4. trace out myXML
  5. (or at some point later) finish loading xml file

Upvotes: 0

Tim D'Haene
Tim D'Haene

Reputation: 1213

You should declare your XML variable outside your function in order to be able to use it in another function

private var myXML:XML;

Upvotes: 0

Related Questions