Question

I want to make some function, with returning loading object. Something like:

   var myVar:String;
   myVar = MyFuncs.GetResponse("http://www....");

And GetResponse function must return some string value, for example json-like text. I try.. But cant understend.

  public function GetResponse(url:String):String{
     var request:URLRequest = new URLRequest(url);
     var loader:URLLoader = new URLLoader();             
     loader.load(request);  
     return loader.data
  }

But data is not loaded yet, when I return the value. I understand, I need to add listener, when loader is complete:

loader.addEventListener(Event.COMPLETE, Complete);

But cant understand, how can I return the loaded value, when the loading is complete. Because it will be a another function..

Please, help, if someone know, how :)

Sorry for my English, please.

Was it helpful?

Solution

You can create a custom loader, and set a callback function to it, when the loader load complete, the callback will be executed. Here is a simple example

public class MyLoader extends Loader
{

    public function MyLoader($callBack:Function = null)
    {
        super();

        callBack = $callBack; 

        this.contentLoaderInfo.addEventListener(Event.COMPLETE, Complete);
    }

    private var callBack:Function;

    private var _url:String;

    public function set url(value:String):void {

        if (_url != value) {
            _url = value;
            var request:URLRequest = new URLRequest(_url);
            this.load(request); 
        }
    }

    protected function Complete(event:Event):void {
        var target:Object = event.target;

        if (callBack) {
            callBack.apply(null, [target]);
        }
    }

And you can use it like this in class A

public function class A {

   public function test():void {

       var loader:MyLoader = new MyLoader(setData);
       loader.url = "assets/pig.jpg";//you asset url
   }

  private function setData(obj:Object):void {
     //the obj type is LoadInfo
  }


}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top