Load map features images into cache rather than have Image components load them each...
[potlatch2.git] / net / systemeD / potlatch2 / utils / CachedDataLoader.as
1 package net.systemeD.potlatch2.utils {
2
3         import flash.events.*;
4         import flash.net.*;
5         import flash.utils.ByteArray;
6
7     import net.systemeD.halcyon.ExtendedURLLoader;
8
9         public class CachedDataLoader {
10
11         private static var allData:Object = {};
12         private static var requestsMade:Object = {};
13         
14                 public static function loadData(url:String, onLoadHandler:Function = null):ByteArray {
15                     var data:ByteArray = allData[url];
16                     if ( data != null )
17                         return data;
18                     
19                     var requests:Array = requestsMade[url];
20                     if ( requests == null ) {
21                         requests = [];
22                         requestsMade[url] = requests;
23
24                     var loader:ExtendedURLLoader = new ExtendedURLLoader();
25                     loader.info = url;
26                 loader.addEventListener(Event.COMPLETE, imageLoaded);
27                 loader.dataFormat = URLLoaderDataFormat.BINARY;
28                 loader.load(new URLRequest(url));
29                     }
30                     requests.push(onLoadHandler);
31                     
32                     return allData[url];
33                 }
34
35         private static function imageLoaded(event:Event):void {
36             var loader:ExtendedURLLoader = ExtendedURLLoader(event.target);
37             var url:String = loader.info as String;
38             allData[url] = loader.data;
39             
40             var requests:Array = requestsMade[url];
41             for each ( var handler:Function in requests ) {
42                 handler(url, loader.data);
43             }
44             
45             delete requestsMade[url];
46         }
47         }
48 }