Showing posts with label loading. Show all posts
Showing posts with label loading. Show all posts

Tuesday, May 25, 2010

Loading Queue in Actionscript

There comes a time when in an actionscript project you have to load a bunch of assets and have them all be ready before calling the setup function that operates on those loaded assets.
The solution for this recurring problem should be standardized, and separated into its own class rather than polluting classes concerned with GUI events or with server-side interaction.
We are aiming for a highly reusable and hence simple bulk loader. Regular usage is listed in the following:
  • Pass an array of the requests to the bulk loader class
  • Listen for when the list has completed
  • Listen for when an item has been completed
  • Get the number of remaining items
Here's a simple implementation to this problem. Please report any misbehavior using comments.
package {
    import flash.display.Loader;
    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.net.URLRequest;
    
    public class BulkLoader extends EventDispatcher{
        private var requests:Vector.<URLRequest>;
        private var current:Loader;
        public function BulkLoader(requests:Vector.<URLRequest>) {
            this.requests = requests;
        }
        
        public function start():void {
            if (requests.length == 0return;
            var req:URLRequest = requests.shift();
            current = new Loader();
            current.contentLoaderInfo.addEventListener(Event.COMPLETE, _currentComplete);
            current.load(req);
        }
        
        public function stop():void {
            if (current == nullreturn;
            current.close();
            requests.unshift(current);
            current = null;
        }
        
        private function _currentComplete(e:Event):void {
            current.removeEventListener(Event.COMPLETE, _currentComplete);
            dispatchEvent(new Event(Event.CHANGE));
            if (requests.length == 0)
                dispatchEvent(new Event(Event.COMPLETE));
            else
                start();
        }
    }
}