JAVASCRIPT   7

AssetLoader.js

Guest on 18th May 2021 04:39:50 AM

  1. ///
  2. //  AssetLoader v 1.0
  3. //  Russell Lowke, March 1st
  4. //
  5. //  Copyright (c)  Lowke Media
  6. //  see http://www.lowkemedia.com for more information
  7. //
  8. //  Permission is hereby granted, free of charge, to any person obtaining a
  9. //  copy of this software and associated documentation files (the "Software"),
  10. //  to deal in the Software without restriction, including without limitation
  11. //  the rights to use, copy, modify, merge, publish, distribute, sublicense,
  12. //  and/or sell copies of the Software, and to permit persons to whom the
  13. //  Software is furnished to do so, subject to the following conditions:
  14. //
  15. //  The above copyright notice and this permission notice shall be included in
  16. //  all copies or substantial portions of the Software.
  17. //
  18. //  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. //  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. //  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. //  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. //  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  23. //  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  24. //  IN THE SOFTWARE.
  25. //
  26. //
  27.  
  28. // Starting to convert my AssetLoader AS3 package to JavaScript
  29.  
  30. function AssetLoader()
  31. {  
  32.     if (! AssetLoader.instance) {
  33.         AssetLoader.instance = this;
  34.     } else {
  35.         throw new Error("AssetLoader is a singleton, it should never be created twice.\r" +
  36.                         "Use AssetLoader.instance to get a reference to AssetLoader.");
  37.     }
  38.    
  39.     this.loaders = new Object();            // (object) loaders in use
  40.     this.nLoaders = 0;                      // (uint) # of loaders remaining RENAME? _nLoadersRemaining
  41.     this.nFilesTotal = 0;                   // (uint) # of loaders in this batch RENAME? _nLoadersTotal
  42.     this.percentDone = NaN;                 // (number) percent loaded of nFilesTotal, NaN returned if idle
  43.    
  44.     ///
  45.     // Loads an external file whose file type is determined by its file extension.
  46.     // Once the asset has finished loading it is passed as the 1st argument to a function callback.
  47.     //
  48.     this.loadFile = function(url,           // (string) URL path to asset being loaded. File type is determined by the file extension suffix in the url.
  49.                                             //          Typical file types are .jpg, .mp3, .swf, and .xml.
  50.                             funct,          // (function) callback to which the loaded asset is passed once load has completed.
  51.                             args,           // (array) array of args to be sent to the function along with the loaded asset.
  52.                             obj)            // (object) object to send function callback to
  53.     {
  54.         // determine loader type using file suffix
  55.         var suffix = AssetLoader.stripCGI(url);
  56.         suffix = suffix.slice(suffix.lastIndexOf("."));
  57.         var loaderType = AssetLoader.loaderType(suffix);
  58.        
  59.         if (! loaderType) {
  60.             throw new Error("AssetLoader can't recognize loader type for use loading file with suffix of " + suffix + " and url " + url);
  61.         }
  62.        
  63.         return this.load(url, loaderType, funct, args, obj);    
  64.     }
  65.    
  66.     ///
  67.     // Loads external file as a particular file type using an explicit loader.
  68.     //
  69.     this.load = function(url,               // (string) url URL path to file being loaded.
  70.                          loaderType,        // (string) loader type to use when loading the asset
  71.                          funct,             // (function) callback to which the loaded asset is passed once load has completed.
  72.                          args,              // (array) array of args to be sent to the function along with the loaded asset.
  73.                          obj)               // (object) object to send function callback to
  74.     {
  75.         // use appropriate loader
  76.         var loader;
  77.         switch (loaderType) {
  78.             case AssetLoader.IMAGE:     loader = new LoadImage(url);            break;
  79.             // case AssetLoader.SOUND:      loader = new LoadSound(url);        break;
  80.             // case AssetLoader.DATA:       loader = new LoadData(url);         break;
  81.             // case AssetLoader.XML:        loader = new LoadXML(url);          break;
  82.             // case AssetLoader.BINARY:     loader = new LoadBinary(url);       break;
  83.             // case AssetLoader.VIDEO:      loader = new LoadVideo(url);        break;
  84.            
  85.             default:
  86.                 throw new Error("AssetLoader can't recognize loader type \"" + loaderType + "\" for url " + url);
  87.         }
  88.        
  89.         return this.loadUsing(loader, funct, args, obj);
  90.     }
  91.    
  92.    
  93.     ///
  94.     // Uses a specific ILoad object to load a file.
  95.     //
  96.     this.loadUsing = function(loader,       // (Loader) loader to use when loading asset
  97.                               funct,        // (function) callback to which the loaded asset is passed once load has completed.
  98.                               args,         // (array) array of args to be sent to the function along with the loaded asset.
  99.                               obj)          // (object) object to send function callback to
  100.     {
  101.         $(loader).one(LoadBase.ASSET_LOADED_EVENT, function(evt) {
  102.             if (funct) {
  103.                 funct.apply(obj, [evt.asset].concat(args));
  104.             }
  105.         });
  106.         this.addAssetLoader(loader);
  107.        
  108.         return loader;
  109.     }
  110.  
  111.     ///
  112.     // add a loader to this.loaders
  113.     //
  114.     this.addAssetLoader = function(loader)
  115.     {  
  116.         if (this.nFilesTotal == 0) {
  117.             // dispatch immediate initial progress event
  118.             $(this).trigger($.Event(AssetLoader.PROGRESS_EVENT), [0]);  // "0" progress, starting load
  119.         }
  120.         ++this.nFilesTotal;
  121.            
  122.         // keep _loader reference safe from garbage collection
  123.         this.loaders[loader.id] = loader;
  124.         ++this.nLoaders;
  125.         loader.startLoad();
  126.     }
  127.    
  128.     ///
  129.     // this method is for internal use only.
  130.     // If you need to remove a loader use close().
  131.     //
  132.     // Removes exiting AssetLoader from _loaders queue.
  133.     //
  134.     this.removeAssetLoader = function(loader)
  135.     {  
  136.         loader.dispose();
  137.        
  138.         // and remove loader from _loaders
  139.         this.loaders[loader.id] = null;
  140.         delete this.loaders[loader.id];
  141.         --this.nLoaders;
  142.        
  143.         // if all loaders finished
  144.         if (this.nLoaders == 0) {
  145.                
  146.             // reset counters
  147.             this.nFilesTotal  = 0;
  148.             this.percentDone  = NaN;
  149.            
  150.             LogAs.debug("AssetLoader batch complete.", AssetLoader.DEBUG_BATCH_COMPLETE);
  151.             $(this).trigger($.Event(AssetLoader.BATCH_COMPLETE_EVENT));
  152.         }
  153.     }
  154.    
  155.     this.whenDone = function(funct,     // (function) function to be called when batch finished loading
  156.                              args,      // (array) array of args to be sent to function
  157.                              obj)       // (object) object to send function callback to
  158.     {
  159.         if (this.nFilesTotal == 0) {
  160.             // new DoLater(funct, args);    // SHOULD REALLY CALL funct ON NEXT IDLE
  161.             if (funct) {
  162.                 funct.apply(obj, [args]);
  163.             }
  164.         } else {
  165.             $(this).one(AssetLoader.BATCH_COMPLETE_EVENT, function() {
  166.                 if (funct) {
  167.                     funct.apply(obj, [args]);
  168.                 }
  169.             });
  170.         }
  171.     }
  172.    
  173.    
  174.     this.toString = function() {
  175.         return "[AssetLoader]";
  176.     }
  177.    
  178. };
  179.        
  180. ///
  181. // Returns cleaned URL String stripped of any CGI "?" variables
  182. //
  183. AssetLoader.stripCGI = function(url)            // (string) URL String being stripped
  184. {
  185.     var index = url.indexOf('?');
  186.     if (index > -1) {
  187.         // strip out any "?" CGI data
  188.         url = url.slice(0, index);
  189.     }
  190.     return url;
  191. }
  192.  
  193. ///
  194. // Returns AssetLoader constant indicating file type. <code>null</code> returned if suffix not recognized.
  195. //
  196. AssetLoader.loaderType = function(suffix)       // (string) File suffix such as ".jpg" indicating file type.
  197. {  
  198.     suffix = suffix.toLowerCase();
  199.  
  200.     // find appropriate loader from suffix
  201.     switch (suffix) {
  202.                
  203.         case ".aif": case ".aiff":          // Audio Interchange File Format
  204.         case ".mp3":                        // MPEG-1 Audio Layer 3
  205.         case ".wav":                        // Waveform audio format
  206.             return AssetLoader.SOUND;
  207.                
  208.         case ".bmp":                        // Bitmap image file format
  209.         case ".png":                        // Portable Network Graphics
  210.         case ".jpg": case ".jpeg":          // Joint Photographic Experts Group
  211.             return AssetLoader.IMAGE;
  212.                
  213.         case ".html":                       // Hypertext Markup Language
  214.         case ".txt": case ".text":          // Text (ASCI) data
  215.             return AssetLoader.DATA;
  216.                    
  217.         case ".xml":                        // Extensible Markup Language
  218.         case ".plist":                      // plist xml data
  219.             return AssetLoader.XML;
  220.                
  221.         case ".bin":                        // binary
  222.             return AssetLoader.BINARY;
  223.  
  224.         default:
  225.             return null;            
  226.     }
  227. }
  228.  
  229. // events dispatched
  230. AssetLoader.PROGRESS_EVENT          = "progress_event"
  231. AssetLoader.BATCH_COMPLETE_EVENT    = "batch_complete_event"
  232.    
  233. // loader types
  234. AssetLoader.IMAGE       = "image";          // .bmp, .png, .jpg, .jpeg
  235. AssetLoader.SOUND       = "sound";          // .aif, .aiff, .mp3, .wav
  236. AssetLoader.DATA        = "data";           // .html, .txt, .text
  237. AssetLoader.XML         = "xml";            // .xml, .plist
  238. AssetLoader.BINARY      = "binary";         // .bin
  239.  
  240.  
  241. // error, warning and ifo IDs
  242. // AssetLoader.WARNING_CANT_RECOGNIZE_FILE_TYPE    = 1000;
  243. // AssetLoader.WARNING_CANT_RECOGNIZE_LOADER_TYPE  = 1001;
  244. // AssetLoader.WARNING_FILE_NOT_FOUND              = 1002;
  245. // AssetLoader.WARNING_FILE_CANT_LOAD              = 1003;
  246. // AssetLoader.WARNING_CLASS_NOT_FOUND             = 1004;
  247. // AssetLoader.WARNING_SECURITY_BREACH             = 1005;
  248. // AssetLoader.WARNING_PARSE_ERROR                 = 1006;
  249. // AssetLoader.WARNING_LOAD_TIMEOUT                = 1007;
  250. // AssetLoader.INFO_LOADER_ISSUE                   = 1008;
  251. AssetLoader.INFO_FILE_CLOSED                    = 1009;
  252. AssetLoader.DEBUG_FILE_REQUESTED                = 1010;
  253. AssetLoader.DEBUG_FILE_LOADED                   = 1011;
  254. AssetLoader.DEBUG_BATCH_COMPLETE                = 1012;

Raw Paste


Login or Register to edit or fork this paste. It's free.