我是AS3的新手。希望将我从xml文件加载的数据保存到变量中。然后再调用该变量。
继承我的代码:
package {
import flash.display.MovieClip;
import flash.events.*;
import flash.display.Stage;
import flash.text.TextField;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLLoaderDataFormat;
import flash.net.URLVariables;
public class myClass extends MovieClip {
public static var objectOneTotal:int = 1;
public static var objectOneCurrent:int = 1;
public function myClass() {
var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("beers.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(event:Event):void {
myXML = new XML(event.target.data);
myClass.objectOneCurrent = int(myXML.current);
myClass.objectOneTotal = int(myXML.total);
trace(myClass.objectOneCurrent);
trace(myClass.objectOneTotal);
}
trace(myClass.objectOneCurrent);
trace(myClass.objectOneTotal);
var objectOneStart:int = objectOne.x;
objectOne.x = (objectOneCurrent / objectOneTotal) * (finish.x - objectOneStart);
}
}
}
它做什么:当我运行它时,查看跟踪,它跟踪对象的初始值“1”,然后跟踪从xml加载的值。所以我相信它正在加载数据,但程序只在其余代码之后运行processXML函数。什么的。
我不太确定。但我需要最后两个跟踪来读取xml数据。
由于
答案 0 :(得分:0)
因为AS3是异步的,所以它会在加载XML之前执行整个MyClass
方法。当XML加载时,执行processXML
中定义的代码来处理它。
解决方案是使processXML
句柄设置为object1.x
:
package {
import flash.display.MovieClip;
import flash.events.*;
import flash.display.Stage;
import flash.text.TextField;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLLoaderDataFormat;
import flash.net.URLVariables;
public class myClass extends MovieClip {
public static var objectOneTotal:int = 1;
public static var objectOneCurrent:int = 1;
public function myClass() {
var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("beers.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
// these will fire before the XML is loaded
trace(myClass.objectOneCurrent);
trace(myClass.objectOneTotal);
}
public function processXML(event:Event):void {
myXML = new XML(event.target.data);
myClass.objectOneCurrent = int(myXML.current);
myClass.objectOneTotal = int(myXML.total);
// these fire after the XML is loaded
trace(myClass.objectOneCurrent);
trace(myClass.objectOneTotal);
var objectOneStart:int = objectOne.x;
objectOne.x = (objectOneCurrent / objectOneTotal) * (finish.x - objectOneStart);
}
}
}