Combining URLRequest, URLLoader and Complete Event Listener In Actionscript 3.0?

Chunky Chunk picture Chunky Chunk · Feb 27, 2010 · Viewed 7.2k times · Source

when handling data, i always have to write the following:

var dataSourceRequest:URLRequest = new URLRequest("/path/file.xml");
var dataSourceLoader:URLLoader = new URLLoader(dataSourceRequest);
dataSourceLoader.addEventListener(Event.COMPLETE, handleDataSource);

while i can understand the usefulness of these 2 objects and event listener being separate, since they often work with each other i'd like to know if there is a method that will combine them all? the closest i can get is this, but it's a bit pointless/nesting:

var dataSourceLoader:URLLoader = new URLLoader(new URLRequest("/path/file.xml"));
dataSourceLoader.addEventListener(Event.COMPLETE, handleDataSource);

what i'd really love would be something that automatically combines the URLRequest, URLLoader and completed event listener like this:

var dataSource:Whatever = new Whatever("/path/file.xml", handleDataSource);

Answer

Matt W picture Matt W · Mar 2, 2010

Encapsulate that code into your own class. It could be as simple as this:

package
{
    import flash.events.Event;
    import flash.net.URLLoader;
    import flash.net.URLRequest;

    public class EncapsulatedURLLoader
    {
        protected var _callback:Function;

        public function EncapsulatedURLLoader( dataUrl:String, callback:Function )
        {
            _callback = callback;
            var l:URLLoader = new URLLoader();
            l.addEventListener( Event.COMPLETE, onComplete );
            l.load( new URLRequest( dataUrl ) );
        }

        private function onComplete( event:Event ):void 
        {
            event.target.removeEventListener( Event.COMPLETE, onComplete );
            _callback.call( null, event.target.data );
        }
    }
}

Use it like so:

function onLoaded( data:* ):void
{
    trace( data );
}

var l:EncapsulatedURLLoader = new EncapsulatedURLLoader( "xml/data.xml", onLoaded );