Search code examples
actionscript-3urlloader

URLLoader how to get the URL that was loaded?


Using the URLLoader is there anyway to get the filename of the file that has been loaded?

public function loadCSS():void {
    var urlLoader:URLLoader = new URLLoader();
    urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete);
    urlLoader.load(new URLRequest("cssFile1"));
    urlLoader.load(new URLRequest("cssFile2"));
    urlLoader.load(new URLRequest("cssFile3"));
}

private function urlLoader_complete(evt:Event):void {

    // *****How can I get the file name here?
    var css:String = URLLoader(evt.currentTarget).data;
    // Do lots of stuff

}

Solution

  • First of all, since the load method is asynchronous, those three calls in your code are going to override each other in succession. The only call that will lead to the COMPLETE event being dispatched would be the final one. If you want to load the files asynchronously, you need to create an instance of URLLoader for each one.

    Second, (and more to your question) there are no properties in the URLLoader class that allow you to access the URLRequest that a load() was initially called with.

    A simple way around this would be to extend URLLoader. Eg, if you only needed the url:

    public class MyURLLoader extends URLLoader
    {
        private var _url:String;
    
        public function MyURLLoader(request:URLRequest=null)
        {
            super(request);
        }
    
        override public function load(request:URLRequest):void
        {
            super.load(request);
            _url = request.url;
        }
    
        public function get url():String
        {
            return _url;
        }
    }
    

    Then in your code you could still use a single event handler:

    public function loadAllCSS():void {
        loadCSSFile("cssFile1");
        loadCSSFile("cssFile2");
        loadCSSFile("cssFile3");
    }
    
    private function loadCSSFile(cssURL:String):void {
        var urlLoader:MyURLLoader = new MyURLLoader();
        urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete);
        urlLoader.load(new URLRequest(cssURL));
    }
    
    private function urlLoader_complete(evt:Event):void {
        var cssURL:String = evt.target.url;  //now I know where this came from
        var css:String = evt.data;
    }