-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdavid.bootstrap.js
More file actions
1228 lines (1088 loc) · 45.8 KB
/
david.bootstrap.js
File metadata and controls
1228 lines (1088 loc) · 45.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*====================================
Bootstrapper for loading David Libraries
The david.bootstrap library will load modules using the AMD style.
This module is standalone and does not required any other modules to be loaded.
This module will load jQuery, underscore, and backbone.
No other modules will load until the bootstrap has completed it's load
DEFINTIONS:
===========
MODULE : a module or .js file, this can either be a module name or a relative url to a module.
If using a module name, then module will be loaded from the same location as the bootstrap.
If using a relative url, the url is relative to the file the module is being loaded from.
e.g. "david" or "david.js"
NAME : a name to define a module, should not match a module that is defined in .js
e.g. "myModule"
MODULELIST : an array of one or more MODULEs
e.g. ["david", "david.utilities"]
CALLBACK : a function which takes parameters equivalent to the MODULELIST of the call
e.g. function(toDavid, toUtilities){// Do something}
DEFINITION : a function which returns an object representation of a module and its functions,
this function should take parameters equivalent to the MODULELIST of the call
e.g. function(toDavid, toUtilities){ return { doSomething: {}};}
EXAMPLES:
=========
// Load javascript module(s)
require(MODULELIST);
// Load javascript modules(s) and execute a function after all modueles have loaded
require(MODULELIST, CALLBACK);
// Get a reference to a loaded module
require(MODULE);
// Defining an anonymous module
define(DEFINITION);
// Defining a named module
define(NAME, DEFINITION);
// Defining an anonymous module with required modules
define(MODULELIST, DEFINITION);
// Defining a named module with required modules
define(NAME, MODULELIST, DEFINITION)
// Adjusting the configuration of the bootstrap
require.config({
cachebuster : __CACHEBUSTER__,
debug : __DEBUG__,
baseUrl: "/resources/inc/javascript/",
paths: {
"underscore" : "/resources/inc/javascript/lib/underscore.js",
"backbone" : "/resources/inc/javascript/lib/backbone-min.js",
"jquery" : "/resources/inc/javascript/lib/jquery-1.7.min.js"
}
});
// Config object parameters:
// cachbuster, a version number or string appended to each of the module urls to break caching on version updates
// debug, a boolean value to turn on or of debugging, this will start or stop messages to the console if available
// baseUrl, the root url to load modules from
// paths, an object with properties representing paths to specific modules
====================================*/
// TODO: Implement using the sessionID as part of the url if david.browser is available
// Create global variables
var require, define;
(function() {
var __CACHEBUSTER__ = 1.0 // Modify this to change the version number
var __DEBUG__ = false; // Set to false to turn off console messages
// TODO: Make LOCKEXCEPTIONS configurable using require.config
var __LOCKEXCEPTIONS__ = ["jquery", "backbone", "underscore"]; // The modules that can be defined even if locked
var g_oBase = this; // Reference to the container (window or server usually)
/**
* We include index of here so that the bootstrap can be used standalone
* Return the integer value of the index of the object in the array
* Returns -1 if the object is not found
*/
Array.prototype.indexOf = Array.prototype.indexOf || function(toObject /*, from */)
{
var lnFrom = Number(arguments[1]) || 0;
lnFrom = (lnFrom < 0) ? 0 : Math.floor(lnFrom);
for (var lnLength = this.length; lnFrom<lnLength;lnFrom++)
{
if (this[lnFrom] === toObject)
{
return lnFrom;
}
}
return -1;
};
/**
* Pads the string on the left using the character provided, ensures the string is
* no longer than tnFinal length after padding.
*/
String.prototype.padLeft = function(tcPadPattern, tnFinalLength)
{
var loRE = new RegExp(".{" + tnFinalLength + "}$");
var lcPadding = "";
do
{
lcPadding += tcPadPattern;
} while(lcPadding.length < tnFinalLength);
return loRE.exec(lcPadding + this);
}
// Ensure david is defined
g_oBase.david = typeof(g_oBase.david) == 'undefined' ? function(){} : window.david;
// Create david.utilities for some required utilities, these will be overwritten by the real david.utilities when it is loaded
g_oBase.david.utilities = typeof(g_oBase.utilities) == 'undefined' ?
{
// Checks if the object is of the type specified.
isType : function(toObject, tcType)
{return Object.prototype.toString.call(toObject) === ("[object " + tcType + "]");},
/**
* Takes a URL and "Cleans" it by adding to the url, the default is to add the version from cachebuster
* This can be overridden in other modules
*/
cleanURL : function(tcURL)
{return tcURL + (tcURL.indexOf("?") < 0 ? "?" : "&") + "version=" + require.config.cachebuster;}
} :
david.utilities;
// Create the Bootstrap Object (Singleton)
david.Bootstrap = (function(){
//-------------------------------
// Private member variables
//-------------------------------
// Contains the list of modules
var m_oModules = {};
// Number of modules that need to be loaded
var m_nModuleCount = 0;
// Number of modules that have been loaded
var m_nLoadedModules = 0;
// Stores the splash screen if it has been created
var m_oSplash;
// Stores the timeout for appending the splash screen
var m_nSplashTimeout;
// Stores the list of paths for module lookups
var m_oPaths = {};
// Stores if the bootstrap is ready for use
var m_lLocked = true;
//-------------------------------
// Private member functions
//-------------------------------
/**
* Checks if all of the modules have finished loading
*/
var isModuleLoadComplete = function()
{
for (var lcModule in m_oModules)
{
if (!m_oModules[lcModule].isCompleted())
{
return false;
}
}
return true;
};
return {
/**
* Loads the specified module, the module can be a string or an array of dependencies
* taModules - the FULL url to the module specified.
* usage example:
* No URL specified
* david.Bootstrap.loadModule("david.utilities");
* URL specified
* david.Bootstrap.loadModule("customDir/customJS");
* Dependiencies
* david.Bootstrap.loadModule(["david.utilities", "customDir/customJS"]);
* Returns the a reference to the module
*/
loadModule : function(taModules, toCallback)
{
console.debug("Loading " + taModules);
var llModule = david.utilities.isType(taModules, "Array");
// Ensure that the module is always in an array
taModules = llModule ? taModules : [taModules];
var lcModuleName = llModule ?
( this.getModule(taModules.toString()) == null ?
"[" + taModules.toString() + "]" :
taModules.toString()) :
taModules[0];
// Get the module, if it does not already exist, add it here
var loModule = this.getModule(lcModuleName);
console.debug(loModule == null ? "Preparing to load "+ lcModuleName : lcModuleName + " already loaded");
loModule = loModule == null ? david.Bootstrap.addModule({
name : llModule ? lcModuleName : taModules[0],
dependencies : llModule ? taModules : [],
anonymous: llModule}) :
loModule;
// Add the callback to the module, if the module is completed loading, this will be executed here
(taModules.length == 1 ?
this.getModule(taModules.toString()) :
this.getModule(lcModuleName)).addLoadedCallback(toCallback);
loModule.plugin.load(loModule);
return loModule;
},
/***
* Adds the module to the list of available modules.
* toModule, an object with a name and dependencies
*/
addModule : function(toModule)
{
// TODO: Remove this support when no longer used
// Support for old ("lib/ckeditor/adapters/jquery", 100, ["lib/ckeditor/ckeditor"]);
if (arguments.length == 3 && david.utilities.isType(toModule, "String"))
{
toModule = {name: toModule,dependencies: arguments[2]};
}
// If the module is not already in the list
var loModule = this.getModule(toModule.name);
if (loModule == null)
{
// Create the module and add it to the list of available modules
loModule = new david.Bootstrap.Module({
name : toModule.name,
dependencies : toModule.dependencies,
anonymous : toModule.anonymous,
definition: toModule.definition
});
m_oModules[loModule.getName()] = loModule;
}
else
{
console.debug("Adjusting Module [" + toModule.name + "]");
loModule.setDefinition(loModule.resolveDefinition(toModule.definition));
// Ensure all of the dependencies are pushed on to the module
for (var i=0, lnLength=toModule.dependencies.length; i<lnLength; i++)
{
loModule.addDependency(toModule.dependencies[i]);
}
// If this module is loaded then we need to force the dependencies
loModule.complete();
}
return loModule;
},
/**
* Gets the module specified, this should be the full context to the module
* tcModuleName the name of the module or a module object
*/
getModule : function(toModule)
{
return m_oModules[david.utilities.isType(toModule, 'String') ? david.Bootstrap.extractModuleInfo(toModule).name : toModule.getName()] || null;
},
/**
* helper function to extract the name and path from the url
*/
extractModuleInfo : function(tcModuleURL)
{
var llAnonymous = !david.utilities.isType(tcModuleURL, "String");
tcModuleURL = (llAnonymous ? tcModuleURL.toString() : tcModuleURL).toLowerCase();
var loInfo = null;
if (/^\[.+/.test(tcModuleURL))
{
loInfo = {
name : tcModuleURL,
path : "",
plugin : ""
};
}
else
{
loInfo = {
name : ((llAnonymous ? tcModuleURL : tcModuleURL.replace(/^.+!|.js$/g, "")).replace(david.Bootstrap.getDefaultRoot(), "")).toLowerCase(),
path : llAnonymous ? "" : tcModuleURL.replace(/^.+!|[^/]+(.js)?$|^http[s]?:\/\/[^/]+/g, ""),
plugin : llAnonymous ? "" : tcModuleURL.replace(/!?[^!]+$/g, "")
};
loInfo.path = (/^[./]/.test(loInfo.path)) ? loInfo.path : david.Bootstrap.getDefaultRoot() + loInfo.path;
}
return loInfo;
},
/**
* Adds a path for the specified module. After the path has been
* set, loading this module will always happen from the path specified.
* This will overwrite any old path
*/
setPath : function(tcModuleName, tcPath)
{
m_oPaths[tcModuleName] = tcPath;
},
/**
* Gets the full path for the module specified
*/
getPath : function(tcModuleName, tcModulePath)
{
return m_oPaths[tcModuleName] || tcModulePath + tcModuleName.replace(/^.+\//g, "");
},
/**
* increases the number of modules that are loaded
*/
incrementLoadedModules :function()
{
m_nLoadedModules++;
this.setStatus("Loaded " + m_nLoadedModules + " / " + m_nModuleCount + " modules");
},
/**
* Increases the number of modules to load
*/
incrementModuleCount : function()
{
m_nModuleCount++;
},
/**
* Gets the total number of modules that are being loaded
**/
getModuleCount :function()
{
return m_nModuleCount;
},
/**
* Gets the number of bytes that are loaded
*/
getLoadedModules:function()
{
return m_nLoadedModules;
},
/**
* Sets the status of the load, if david is loaded, this will use
* david to create a status bar
*/
setStatus : function(tcStatus)
{
console.debug(tcStatus);
if (david.setStatus)
{
david.setStatus(tcStatus);
}
},
/**
* unlocks the bootstrap for external use
*/
unlock : function()
{
m_lLocked = false;
},
/**
* Checks if the bootstrap is locked
*/
isLocked : function()
{
return m_lLocked;
},
/**
* Function that occurs when a module has completed its load
*/
onCompletedModule : function (toModule)
{
// If all the modules are complete, then hide the splash screen
if (isModuleLoadComplete())
{
this.hideSplash();
}
},
/**
* Gets the root of the modules if one is not provided
*/
getDefaultRoot : function()
{
return require.config.baseUrl;
},
/**
* Creates the splash screen if needed, then displays it
*/
showSplash : function()
{
if (!m_oSplash)
{
m_oSplash = document.getElementById("grpSplash") || document.createElement("div");
m_oSplash.style.width = Math.max(
Math.max(document.body.scrollWidth, document.documentElement.scrollWidth),
Math.max(document.body.offsetWidth, document.documentElement.offsetWidth),
Math.max(document.body.clientWidth, document.documentElement.clientWidth)
)+ "px";
m_oSplash.style.height = Math.max(
Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
Math.max(document.body.clientHeight, document.documentElement.clientHeight)
)+ "px";
m_oSplash.style.position = "absolute";
m_oSplash.style.top = "0px";
m_oSplash.style.left = "0px";
m_oSplash.style.background = "white url('/resources/images/ajax-loader.gif') no-repeat center";
m_oSplash.id="grpSplash";
this.appendSplashWhenReady();
}
},
/**
* this defers display of the splash screen until it is safe
*/
appendSplashWhenReady : function()
{
if (m_oSplash.parentElement == null)
{
try
{
// IE6 may throw an error if it is not in a state where it can append
document.body.appendChild(m_oSplash);
}
catch (loEX)
{
m_nSplashTimeout = window.setTimeout(david.Bootstrap.appendSplashWhenReady, 10);
}
}
},
/**
* Hides the splash screen if it is displayed
*/
hideSplash : function()
{
if (m_nSplashTimeout != 0)
{
window.clearTimeout(m_nSplashTimeout);
m_nSplashTimeout = -1;
}
var loFunction = function(){
if (m_oSplash && m_oSplash.parentNode)
{
m_oSplash.parentNode.removeChild(m_oSplash);
m_oSplash = null;
}
};
if ($jQ != null)
{
$jQ("#grpSplash").fadeOut("fast",loFunction);
}
else
{
loFunction();
}
}
};
})();
/**
* The module class, encapsulates the concept of a module
*/
david.Bootstrap.Module = (function()
{
/**
* Constructor function. Creates a new instance of Module
* Takes an object as a parameter, the object should have the following properties
* dependencies, the string list of dependent modules
* name, the name of the module
*/
return function(toModule)
{
//-------------------------------
// Private member variables
//-------------------------------
// Name of the module
var m_cName = "";
// The path for the module
var m_cPath = "";
// List of dependency keys
var m_aDependencies = [];
// Reference to the script tag for this module
var m_oTag = null;
// contains the results of the executed module
var m_oDefinition = null;
// stores the flag indicating a module has completed
var m_lIsCompleted = false;
// stores the list of callbacks to run when this module is loaded
var m_aLoadedCallbacks = [];
// Stores if this was an anonymous module
var m_lAnonymous = false;
// Store the parent modules, or the modules requiring this module
var m_aParents = [];
// Store if the extension of .js should be added to the file
var m_lForceJS = true;
//-------------------------------
// Privileged functions
//-------------------------------
// GETS/SETS the name of the module
this.getName = function(){return m_cName;};
this.setName = function(tcName){m_cName = tcName.toLowerCase();};
/**
* Check if this module has completed its load, completed means both
* loaded and all callbacks have been called
*/
this.isCompleted = function(){return m_lIsCompleted && (this.isLoading() || this.isAnonymous())};// && m_aLoadedCallbacks.length == 0};
this.setCompleted = function(){console.debug("Completing module " + this.getName());m_lIsCompleted = true;};
/**
* Get the list of modules that require this module
*/
this.getParents = function(){return m_aParents};
/**
* Checks if this module is an anonymous module or not
*/
this.isAnonymous = function(){return m_lAnonymous;};
this.setAnonymous = function(tlAnonymous){m_lAnonymous = tlAnonymous;};
// GETS/SETS the path of this module
this.getPath = function(){return m_cPath};
this.setPath = function(tcPath){m_cPath = tcPath;};
/**
* Gets or sets if the .js extension should be added to a file if it does not
* already exist.
*/
this.forceJS = function(tlJS)
{
if (typeof(tlJS) != "undefined")
{
m_lForceJS = tlJS;
}
return m_lForceJS;
};
// GETS the URL for this module
this.getURL = function(){
return david.utilities.cleanURL(david.Bootstrap.getPath(this.getName(), this.getPath()).replace(/\.js$/, "") + (this.forceJS() ? ".js" : ""));};
// GET/SET the script tag that is associated with this module
this.setTag = function(toTag){m_oTag = toTag;};
this.getTag = function(){return m_oTag;};
// Gets/Sets the definition of this module
this.getDefinition = function(){return m_oDefinition};
this.setDefinition = function(toDefinition)
{
console.debug("Setting definition of " + this.getName() + " to " + toDefinition);
m_oDefinition = toDefinition
};
/**
* Checks if this module has been marked as loaded, loaded means
* any scripts have been attached, or a definition has been added
*/
this.isLoading = function(){return this.getTag() != null || m_oDefinition != null};
/***
* Adds the specified module as a dependent of this module
* tcName - the name of the javascript file to add as a module.
*/
this.addDependency = function(tcName)
{
var loInfo = david.Bootstrap.extractModuleInfo(tcName);
// Make sure this module did not already have it as a dependency
// No need to report an error if dependency already exists
var lnIndex = this.getDependency(loInfo.name);
if (lnIndex < 0)
{
console.debug("Adding dependency " + loInfo.name + " to " + this.getName());
m_aDependencies.push(loInfo.name);
var loModule = david.Bootstrap.getModule(tcName) || david.Bootstrap.addModule({
name : tcName,
dependencies : []
});
loModule.addParent(this);
var lcPlugin = loInfo.plugin;
if (lcPlugin != "")
{
// TODO: Adjust model to allow multiple plugins, e.g. order!text!
lcPlugin = "david.bootstrap." + lcPlugin;
console.debug("Using plugin `" + lcPlugin + "` to load [" + loModule.getName() + "]");
// There is a plugin being loaded for this module, so don't allow a regular load
loModule.plugin.load = function(){};
// Load the plugin if needed
require([lcPlugin],
function(toPlugin){
console.debug("Completed loading plugin " + lcPlugin);
loModule.plugin = toPlugin;
loModule.plugin.load(loModule);
});
}
}
};
// GETS the list of dependencies if there are any
this.getDependencies = function(){return m_aDependencies;};
// Gets the index of the specified dependency
this.getDependency = function(tcModule){return m_aDependencies.indexOf(tcModule);};
/**
* Adds a callback to this module. When this module and all of its
* dependencies are loaded, this callback will be executed
*/
this.addLoadedCallback = function(toCallback)
{
this.insertLoadedCallback(m_aLoadedCallbacks.length, toCallback);
};
/**
* Inserts a callback at the specified index
*/
this.insertLoadedCallback = function(tnIndex, toCallback)
{
if (!toCallback) {return;}
tnIndex = tnIndex < 0 ? 0 : tnIndex;
tnIndex = tnIndex > m_aLoadedCallbacks.length ? m_aLoadedCallbacks : tnIndex;
console.debug("Adding callback at index " + tnIndex + " to " + this.getName());
if (m_aLoadedCallbacks.indexOf(toCallback) < 0)
{
m_aLoadedCallbacks.splice(tnIndex, 0, toCallback);
}
// If the module is already completed then just execute the callbacks
if (this.isCompleted())
{
console.debug("Module is completed, executing callbacks");
this.executeLoadedCallbacks();
}
};
/**
* Checks if there are oustanding callbacks
*/
this.hasCallbackFunctions = function(){return m_aLoadedCallbacks && m_aLoadedCallbacks.length > 0;};
/**
* This executes the callbacks when this module is completely loaded
*/
this.executeLoadedCallbacks = function()
{
console.debug("Executing callbacks for " + this.getName());
for (var i=0, lnLength = m_aLoadedCallbacks.length; i<lnLength; i++)
{
var laArgs = this.getCallbackArguments();
laArgs = this.isAnonymous() && !this.getDefinition() ? laArgs.splice(1, laArgs.length) : laArgs;
console.debug("Executing" + (this.isAnonymous() ? " Anonymous " : "") + " module " + this.getName() + " callback " + (i + 1) + "/" + lnLength + "\n\targs: [" + laArgs + "]");
try
{
var loResult = m_aLoadedCallbacks[i].apply(this, laArgs);
if (loResult && !this.getDefinition())
{
this.setDefinition(loResult);
}
}
catch(ex)
{
console.error("Callback failed - \n" + m_aLoadedCallbacks[i] + "\n\n\n" + ex);
throw ex;
}
}
m_aLoadedCallbacks.length = 0;
}
// Gets an array of dependency objects which can be passed to a callback
this.getCallbackArguments = function()
{
var laDependencies = this.getDependencies();
var loArgs = [this.getDefinition()];
for (var i=0, lnLength = laDependencies.length; i<lnLength; i++)
{
if (laDependencies[i] === "require")
{
console.debug("REQUIRE!");
loArgs[i+1] = {};
}
else if (laDependencies[i] === "exports")
{
console.debug("exports!");
loArgs[i+1] = {};
}
else if (laDependencies[i] === "module")
{
console.debug("module!");
loArgs[i+1] = {
id:this.getName(),
uri:this.getURL(),
exports:{}
};
}
else
{
loArgs[i+1] = david.Bootstrap.getModule(laDependencies[i]).getDefinition();
}
console.debug("pushed " + laDependencies[i] + "\n" + " to argument " + (i+1));
}
return loArgs;
}
// Set up the default plugin
this.plugin = {load : function(toModule){toModule.load();}, onLoaded : function(toModule){}};
//-------------------------------
// Initialisation function
//-------------------------------
var loInfo = david.Bootstrap.extractModuleInfo(toModule.name);
this.setName(toModule.anonymous ? toModule.name : loInfo.name);
this.setPath(loInfo.path);
this.setDefinition(toModule.definition ? toModule.definition : null);
this.setAnonymous(toModule.anonymous ? true : m_lAnonymous);
david.Bootstrap.incrementModuleCount();
for (var i=0, lnLength = (toModule.dependencies || []).length; i<lnLength; i++)
{
this.addDependency(toModule.dependencies[i]);
}
};
})();
//-------------------------------
// NON - Privileged functions
//-------------------------------
david.Bootstrap.Module.prototype =
{
/**
* Adds a parent module, a parent module is a module which requires
* this module
*/
addParent : function(toParent)
{
var laParents = this.getParents();
if (laParents.indexOf(toParent) <0)
{
laParents.push(toParent);
}
},
/**
* This will load all of the dependencies for this module, this will
* return true if there is still a lock in place after this call
*/
loadDependencies : function()
{
console.debug("Loading dependencies for " + this.getName());
var laDependencies = this.getDependencies();
var llLoadingLocked = false;
// Attempt to load each dependency that is not synch locked
for (var i=0, lnLength = laDependencies.length; i<lnLength; i++)
{
var lcDependency = laDependencies[i];
// Get the module
var loModule = david.Bootstrap.getModule(lcDependency);
if (!loModule.isLoading())
{
console.debug("Loading module " + loModule.getName());
loModule.plugin.load(loModule);
}
}
return llLoadingLocked;
},
/***
* Adds the script tag to the page
* tcURL - The url for the tag source
*/
addScriptTag : function()
{
if (!this.isAnonymous() && !this.getTag())
{
var lcURL = this.getURL();
console.debug("Adding script for " + this.getName() + " ("+ lcURL + ")");
// Check if a script already exists on the page with this module
var laScripts = document.getElementsByTagName("script");
for (var i=0, lnLength = laScripts.length; i<lnLength; i++)
{
// TODO: Need more testing on this, particularly with the urls with parameters
if (laScripts[i].src === lcURL)
{
console.debug("Reusing script - " + lcURL);
this.setTag(laScripts[i]);
return;
}
}
// Make sure we are ready
var loTag = document.createElement("script");
loTag.src = lcURL;
loTag.type = "text/javascript";
loTag.charset = "utf-8";
loTag.async = true;
loTag.module = this;
this.setTag(loTag);
this.addEventListener(loTag, this.onScriptLoaded, typeof(loTag.readyState) != 'undefined' ? "readystatechange" : "load");
document.getElementsByTagName("head")[0].appendChild(loTag);
}
},
/**
* Adds an event listener to the element specified
*/
addEventListener : function(toElement, toCallback, tcEventType)
{
if (toElement.addEventListener)
{
toElement.addEventListener(tcEventType, function(e){
toCallback(e)
}, false);
}
else if (toElement.attachEvent)
{
toElement.attachEvent("on" + tcEventType, function(e){
toCallback(window.event)
});
}
},
/**
* Event handler for loading of the script tag
*/
onScriptLoaded : function(toEvent)
{
var loTag = toEvent.currentTarget || toEvent.srcElement;
if (toEvent.type === "load" || (loTag && /^(complete|loaded)$/.test(loTag.readyState)));
{
var loModule = loTag.module;
var loOutstanding = david.Bootstrap.outstanding;
david.Bootstrap.outstanding = undefined;
console.debug("Script loaded for module " + loModule.getName());
if (toEvent.type === "load" || loTag.readyState === "loaded" || loTag.readyState === "complete")
{
console.debug("Anonymous script found - " + loTag.src);
// Follows AMD
if (loOutstanding)
{
console.debug("Linking Anonymous script");
if (loOutstanding.dependencies)
{
for (var i=0, lnLength = loOutstanding.dependencies.length; i<lnLength; i++)
{
loModule.addDependency(loOutstanding.dependencies[i]);
}
}
loModule.setAnonymous(true);
loModule.insertLoadedCallback(0, loOutstanding.definition);
}
// Detach events
if (loTag.detachEvent)
{
loTag.detachEvent("onreadystatechange", loModule.onScriptLoaded);
}
else
{
loTag.removeEventListener("load", loModule.onScriptLoaded, false);
}
loTag.module = null;
loModule.complete();
}
}
},
/**
* Attempts to complete the loading of this module
*/
complete : function()
{
// This can only be set as complete if all the dependencies are loaded
var laDependencies = this.getDependencies();
console.debug("Checking dependencies for " + this.getName());
for (var i=0, lnLength = laDependencies.length; i<lnLength; i++)
{
var loModule = david.Bootstrap.getModule(laDependencies[i]);
if (!loModule.isLoading())
{
console.debug(loModule.getName() + " has not started loading yet");
this.loadDependencies()
return;
}
else if (!loModule.isCompleted())
{
console.debug(loModule.getName() + " is not yet completed");
return;
}
}
console.debug("Dependency check complete for " + this.getName());
if (!this.isCompleted())
{
this.setCompleted();
if (this.isCompleted())
{
this.executeLoadedCallbacks();
david.Bootstrap.incrementLoadedModules();
// Load any dependent parents
var laParents = this.getParents();
for (i=0, lnLength = laParents.length; i<lnLength; i++)
{
if (!laParents[i].isCompleted())
{
laParents[i].complete();
}
}
this.plugin.onLoaded(this);
david.Bootstrap.onCompletedModule(this);
}
}
},
/**
* Loads the module, loading takes place by adding a script tag to the head of the html
* if one does not already exist
*/
load : function()
{
if ((this.isAnonymous() || !this.isLoading()) && !this.isCompleted())
{
if (!this.loadDependencies())
{
// The dependencies have loaded and there are no locks in place
if (this.isAnonymous())
{
console.debug("Starting Anonymous load for " + this.getName());
// No script needed, we are complete
this.complete();
}
else
{
console.debug("Starting script load for " + this.getName());
this.addScriptTag();
}
}
}
},
/**
* Resolved the definition supplied into a value
*/
resolveDefinition : function(toDefinition)
{
if (david.utilities.isType(toDefinition, "Function"))
{
// Update the status
var loArgs = this.getCallbackArguments();
console.debug("Resolving Definition for " + this.getName());
return toDefinition.apply(this.getDefinition(), loArgs.length > 1 ? loArgs.splice(1) : [this.getDefinition()]);
}
return toDefinition;
}
};
// Store the object in require if needed, it may be a config argument
var m_oOldRequire = require;