开发者

as3: Loading XML into a my class' property doesn't seem to do what I would expect

开发者 https://www.devze.com 2022-12-16 11:03 出处:网络
This seems like it should be an easy one but I can\'t figure it out. I\'m trying out a very simple class that, when created,开发者_如何学运维 loads and XML file into the class\'s property. I must be

This seems like it should be an easy one but I can't figure it out.

I'm trying out a very simple class that, when created,开发者_如何学运维 loads and XML file into the class's property. I must be getting a basic concept tangled up here because I can see the XML coming in just fine in the handleComplete function, but the class property _result remains empty.

What concept am I missing here?

Thanks in advance.

public class MyClass
{
    private var _result;

    public function MyClass()
    {
        var url:String = 'myFile.xml';
        var loader:URLLoader = new URLLoader();
        loader.addEventListener( Event.COMPLETE, handleComplete );
        loader.load( new URLRequest( url ) );

        trace(_result); //returns nothing... didn't I just load it?
    }

    private function handleComplete( event:Event ) : void
    {
        try
        {
            var res:XML = new XML( event.target.data );
            _result = res;

            trace(_result); // this writes the myFile.xml to command line as I would expect.
        }
        catch ( e:TypeError )
        {
            // some error handling code
        }
    }
}

}


The reason that the first trace prints nothing is because the request for the file is not synchronous. This means that it runs in the background and only when it is done (which could take a while if the file is very large or the network connection shaky) does it call the handleComplete function.

At the time your first trace() is called, handleComplete has not been called yet because the file has not finished loading yet.

0

精彩评论

暂无评论...
验证码 换一张
取 消