Actionscript 3: Force program to wait until event handler is called

Posted by Jeremy Swinarton on Stack Overflow See other posts from Stack Overflow or by Jeremy Swinarton
Published on 2010-04-03T21:20:19Z Indexed on 2010/04/03 21:23 UTC
Read the original article Hit count: 866

Filed under:
|
|

I have an AS 3.0 class that loads a JSON file in using a URLRequest.

package {

    import flash.display.MovieClip;
    import flash.display.Loader;
    import flash.net.URLRequest;
    import flash.net.URLLoader;
    import flash.events.Event;

    public class Tiles extends MovieClip {

        private var mapWidth:int,mapHeight:int;
        private var mapFile:String;

        private var mapLoaded:Boolean=false;

        public function Tiles(m:String) {

            init(m);

        }

        private function init(m:String):void {

            // Initiates the map arrays for later use.
            mapFile=m;

            // Load the map file in.
            var loader:URLLoader = new URLLoader();
            loader.addEventListener(Event.COMPLETE, mapHandler);
            loader.load(new URLRequest("maps/" + mapFile));


        }

        private function mapHandler(e:Event):void {

            mapLoaded=true;
            mapWidth=3000;

        }

        public function getMapWidth():int {

            if (mapLoaded) {

                return (mapWidth);

            } else {

                getMapWidth();
                return(-1);
            }

        }

    }

}

When the file is finished loading, the mapHandler event makes changes to the class properties, which in turn are accessed using the getMapWidth function. However, if the getMapwidth function gets called before it finishes loading, the program will fail.

How can I make the class wait to accept function calls until after the file is loaded?

© Stack Overflow or respective owner

Related posts about flash

Related posts about actionscript-3