开发者

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

}


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;
}


Create three URLLoaders. In the complete function, you can check the identity of the event target to determine which on you're getting the event from, which will tell you which file is loaded. You could also have three different handlers instead, depending in how you want to factor the code.

The docs aren't clear on what happens when you call load multiple times on the same URLLoader, which (to me) means it's not well-defined behavior and you should avoid it. For your example, the documentation doesn't specify whether your event handler will be called once or three times, and if it is called multiple time whether the data will be different each time or not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜