0

我是 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);

    }

}

}

它在做什么:当我运行它时,查看跟踪,它在跟踪从 xml 加载的值之前跟踪“1”的对象初始值。所以我相信它正在加载数据,但程序只在其余代码之后运行 processXML 函数。或者其他的东西。

我不太确定。但我需要最后两个跟踪来读取 xml 数据。

谢谢

4

1 回答 1

0

MyClass因为 AS3 是异步的,所以它会在加载 XML 之前执行整个方法。当 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);

        }
    }
}
于 2013-02-07T09:45:04.847 回答