简体   繁体   中英

Action Script 3 return value from Class

I have AS3 class which parses xml and creates buttons foreach item in XML. However I want to access total number of items later.How can i do that ?

I am using it like this.

var menu:MenuClass = new MenuClass();
trace( menu.aItems() );

Right now it is retuning NAN however If i trace it after line Items = xml.item.length(); it outputs correct number.

package com.lib.menu
{
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.net.URLLoader;
    import flash.net.URLRequest;

    public class MenuClass extends MovieClip {

        private var urlLoader:URLLoader;
        private var urlRequest:URLRequest;
        private const XML_PATH:String = "resources/menu.xml";
        private var xml:XML;
        protected var Items:Number;

        public function MenuClass() {

            urlLoader = new URLLoader();
            urlLoader.load(new URLRequest(XML_PATH));
            urlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
        }
        private function xmlLoaded(e:Event):void 
        {
            xml = new XML(e.target.data);
            Items =  xml.item.length();
            for (var i:int = 0; i < Items; i++) {
                var btn:Button = new Button(xml.item[i].@title,xml.item[i].@image);
                btn.y = Math.floor(i * (btn.height+2)) ;
                addChild(btn);
            }
        }
        public function aItems():Number {
            return Items;
        }

    }

}

URLLoader loads data asynchronously which means the constructor MenuClass does not wait for the loading to complete. When loading of the XML is complete xmlLoaded will be called and a valid value will be set to Items . But you are trying to access Items just after creating the object, ie before xmlLoaded is called. So you are getting NaN at that point.

Ok. I solved this by adding this.dispatchEvent(new Event("MenuComplete")); to end of private function xmlLoaded(e:Event):void and then

var menu:MenuClass = new MenuClass();
menu.addEventListener('MenuComplete', onNext); 
function onNext(e:Event):void{
    trace(menu.aItems());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM