AS3 - Problems with Functions that Return Values of Variables from Loaded Data

298 views Asked by At

I am trying to make a blitting engine, and this part is really giving me a hard time. I am trying to make an external class to do all of the xml parsing from the file that texture packer spits out. I made a class in my utilities package called XmlParserBlit.as

I was hoping to be able to just instantiate it and call the one function for it to do it's job, something like this:

var _xmlParser:XmlParserBlit = new XmlParserBlit();
_blitDataAry = _xmlParser.getAryFromBlitXmlData("blit_test_4.xml");

However, it seems like it's not going to be that easy. The function inside of the XmlParserBlit class has an event listener that triggers a function to happen when the loading is complete. It seems that flash just keeps going on through the function, and the trace("Finished Array: " + _xmlDataAry); just returns a blank array. Is there some way for me to wait for the complete listener to be finished? Or maybe I can back the responsibility on returning a value from getAryFromBlitXmlData over to onXmlLoaded?

I am really stumped, and learning how to beat this problem will open my mind for how to tackle similar problems. Thanks.

public function getAryFromBlitXmlData(xmlPath:String):Array
    {
            _xmlDataAry = []

            _xmlPath = xmlPath;

            _testXml = new XML();
            _testXmlRequest = new URLRequest(_xmlPath);
            _testXmlLoader = new URLLoader();

            _testXmlLoader.addEventListener(Event.COMPLETE, onXmlLoaded);
            _testXmlLoader.load(_testXmlRequest);

            trace("Finished Array: " + _xmlDataAry);

            return _xmlDataAry;

    }

    protected function onXmlLoaded(event:Event):void
    {

        _loadedXML = new XML(event.target.data);

        var theSprites:XMLList = _loadedXML..sprite

            for each ( var _rectSprite:XML in theSprites)
            {

                            //--------------------------------------
                            //  do some string manipulations here
                            //--------------------------------------                        
            }

        var _rectangle:Rectangle = new Rectangle(_xValue, _yValue, _widthValue, _heightValue);

        var miniAry:Array = [_rectangle, _xOffsetValue, _yOffsetValue]

        _xmlDataAry.push(miniAry);


                //* want to return _xmlDataAry to the getAryFromBlitXmlData function

            }


        }
1

There are 1 answers

6
SeiferTim On

onXmlLoaded won't trigger until AFTER the load function finishes asynchronously. Your best bet would be to make getAryFromBlitXmlData not return a value, and handle your _xmlDataArray inside of onXmlLoaded