2

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 {

                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?

Jeremy Swinarton
  • 517
  • 1
  • 5
  • 14
  • Why will the program fail , if the getMapWidth() function is called before complete loading of the file ? Isn't it taken care of, by the recursive getMapWidth() ? – The Machine Apr 03 '10 at 21:28
  • Whoops, forgot to edit that line out. Calling getMapWidth() recursively gave a Stack Overflow error, so that's out of the question. – Jeremy Swinarton Apr 03 '10 at 21:35

2 Answers2

0
 private function mapHandler(e:Event):void {
              if (mapLoaded) {

                mapLoaded=true;
                 mapWidth=3000;
                return (mapWidth);

             } else {

           getMapWidth()

        }

}

        public function getMapWidth():int 
                return(-1);


        }

This might solve your problem, why are checking it in getMapWidth when there is no need of it.

Kevin
  • 23,174
  • 26
  • 81
  • 111
0

Okay, so I figured out what I needed to do. The problem was with the code on my main timeline:

trace(bg.getMapWidth());

I forgot that the code only executed once without an event listener on the main timeline, like this

stage.addEventListener(Event.ENTER_FRAME, n);

function n(e:Event):void
{
    trace(bg.getMapWidth());
}

Now the width is returned once per frame, and everything works properly. Thanks for your help ;)

Jeremy Swinarton
  • 517
  • 1
  • 5
  • 14