LoadingManager.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. class LoadingManager {
  2. constructor( onLoad, onProgress, onError ) {
  3. const scope = this;
  4. let isLoading = false;
  5. let itemsLoaded = 0;
  6. let itemsTotal = 0;
  7. let urlModifier = undefined;
  8. const handlers = [];
  9. // Refer to #5689 for the reason why we don't set .onStart
  10. // in the constructor
  11. this.onStart = undefined;
  12. this.onLoad = onLoad;
  13. this.onProgress = onProgress;
  14. this.onError = onError;
  15. this.itemStart = function ( url ) {
  16. itemsTotal ++;
  17. if ( isLoading === false ) {
  18. if ( scope.onStart !== undefined ) {
  19. scope.onStart( url, itemsLoaded, itemsTotal );
  20. }
  21. }
  22. isLoading = true;
  23. };
  24. this.itemEnd = function ( url ) {
  25. itemsLoaded ++;
  26. if ( scope.onProgress !== undefined ) {
  27. scope.onProgress( url, itemsLoaded, itemsTotal );
  28. }
  29. if ( itemsLoaded === itemsTotal ) {
  30. isLoading = false;
  31. if ( scope.onLoad !== undefined ) {
  32. scope.onLoad();
  33. }
  34. }
  35. };
  36. this.itemError = function ( url ) {
  37. if ( scope.onError !== undefined ) {
  38. scope.onError( url );
  39. }
  40. };
  41. this.resolveURL = function ( url ) {
  42. if ( urlModifier ) {
  43. return urlModifier( url );
  44. }
  45. return url;
  46. };
  47. this.setURLModifier = function ( transform ) {
  48. urlModifier = transform;
  49. return this;
  50. };
  51. this.addHandler = function ( regex, loader ) {
  52. handlers.push( regex, loader );
  53. return this;
  54. };
  55. this.removeHandler = function ( regex ) {
  56. const index = handlers.indexOf( regex );
  57. if ( index !== - 1 ) {
  58. handlers.splice( index, 2 );
  59. }
  60. return this;
  61. };
  62. this.getHandler = function ( file ) {
  63. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  64. const regex = handlers[ i ];
  65. const loader = handlers[ i + 1 ];
  66. if ( regex.global ) regex.lastIndex = 0; // see #17920
  67. if ( regex.test( file ) ) {
  68. return loader;
  69. }
  70. }
  71. return null;
  72. };
  73. }
  74. }
  75. const DefaultLoadingManager = new LoadingManager();
  76. export { DefaultLoadingManager, LoadingManager };