forked from stealjs/steal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
older.js
2016 lines (1771 loc) · 54.6 KB
/
older.js
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
// steal is a resource loader for JavaScript. It is broken into the following parts:
//
// - Helpers - basic utility methods used internally
// - AOP - aspect oriented code helpers
// - Deferred - a minimal deferred implementation
// - Uri - methods for dealing with urls
// - Api - steal's API
// - Resource - an object that represents a resource that is loaded and run and has dependencies.
// - Type - a type systems used to load and run different types of resources
// - Packages - used to define packages
// - Extensions - makes steal pre-load a type based on an extension (ex: .coffee)
// - Mapping - configures steal to load resources in a different location
// - Startup - startup code
// - jQuery - code to make jQuery's readWait work
// - Error Handling - detect scripts failing to load
// - Has option - used to specify that one resources contains multiple other resources
// - Window Load - API for knowing when the window has loaded and all scripts have loaded
// - Interactive - Code for IE
// - Options -
(function( win, undefined ) {
// create the steal function now to use as a namespace.
function steal() {
// convert arguments into an array
var args = map(arguments);
if ( args.length ) {
pending.push.apply(pending, args);
// steal.after is called everytime steal is called
// it kicks off loading these files
steal.after(args);
// return steal for chaining
}
return steal;
};
// ## Helpers ##
// The following are a list of helper methods used internally to steal
var
// check that we have a document
doc = win.document,
docEl = doc && doc.documentElement,
// a jQuery-like $.each
each = function(o, cb) {
var i, len;
// weak array detection, but we only use this internally so don't
// pass it weird stuff
if ( typeof o.length == 'number' ) {
for ( i = 0, len = o.length; i <len; i++) {
cb.call(o[i],i,o[i], o)
}
} else {
for ( i in o ) {
cb.call(o[i],i,o[i], o)
}
}
return o;
},
// if o is a string
isString = function( o ) {
return typeof o == "string";
},
// if o is a function
isFn = function( o ) {
return typeof o == "function";
},
// dummy function
noop = function() {},
// creates an element
createElement = function(nodeName){
return doc.createElement(nodeName)
},
// creates a script tag
scriptTag = function() {
var start = createElement("script");
start.type = "text/javascript";
return start;
},
// minify-able verstion of getElementsByTagName
getElementsByTagName = function( tag ) {
return doc.getElementsByTagName( tag );
},
// A function that returns the head element
// creates and caches the lookup for faster
// performance.
head = function() {
var hd = getElementsByTagName("head")[0];
if (! hd ) {
hd = createElement("head");
docEl.insertBefore(hd, docEl.firstChild);
}
// replace head so it runs fast next time.
head = function(){
return hd;
}
return hd;
},
// extends one object with another
extend = function( d, s ) {
// only extend if we have something to extend
s && each(s, function( k ) {
d[k] = s[k];
});
return d;
},
// makes an array of things, or a mapping of things
map = function( args, cb ) {
var arr = [];
each(args, function(i, str){
arr.push( cb ? ( isString( cb ) ? str[cb] : cb.call( str, str )) : str )
});
return arr;
},
// testing support for various browser behaviors
support = {
// does onerror work in script tags?
error: doc && (function() {
var script = scriptTag();
script.onerror = noop;
return isFn( script.onerror ) || "onerror" in script
})(),
// If scripts support interactive ready state.
// This is tested later.
interactive: false,
// use attachEvent for event listening (IE)
attachEvent : doc && scriptTag().attachEvent
},
// a startup function that will be called when steal is ready
startup = noop,
// if oldsteal is an object
// we use it as options to configure steal
opts = typeof win.steal == "object" ? win.steal : {},
// adds a suffix to the url for cache busting
addSuffix = function(str){
if(opts.suffix){
str = (str + '').indexOf('?') > -1 ?
str + "&" + opts.suffix :
str + "?" + opts.suffix;
}
return str;
};
// ## AOP ##
// Aspect oriented programming helper methods are used to
// weave in functionality into steal's API.
// calls `before` before `f` is called.
// steal.complete = before(steal.complete, f)
// `changeArgs=true` makes before return the same args
function before(f, before, changeArgs){
return changeArgs ?
function before_changeArgs(){
return f.apply(this,before.apply(this,arguments));
}:
function before_args(){
before.apply(this,arguments);
return f.apply(this,arguments);
}
}
// returns a function that calls `after`
// after `f`
function after(f, after, changeRet){
return changeRet ?
function after_CRet(){
return after.apply(this,[f.apply(this,arguments)].concat(map(arguments)));
}:
function after_Ret(){
var ret = f.apply(this,arguments);
after.apply(this,arguments);
return ret;
}
}
// =============================== Deferred .63 ============================
var Deferred = function( func ) {
if ( ! ( this instanceof Deferred ))
return new Deferred();
this.doneFuncs = [];
this.failFuncs = [];
this.resultArgs = null;
this.status = "";
// check for option function: call it with this as context and as first
// parameter, as specified in jQuery api
func && func.call(this, this);
}
Deferred.when = function() {
var args = map( arguments );
if (args.length < 2) {
var obj = args[0];
if (obj && ( isFn( obj.isResolved ) && isFn( obj.isRejected ))) {
return obj;
} else {
return Deferred().resolve(obj);
}
} else {
var df = Deferred(),
done = 0,
// resolve params: params of each resolve, we need to track down
// them to be able to pass them in the correct order if the master
// needs to be resolved
rp = [];
each(args, function(j, arg){
arg.done(function() {
rp[j] = (arguments.length < 2) ? arguments[0] : arguments;
if (++done == args.length) {
df.resolve.apply(df, rp);
}
}).fail(function() {
df.reject(arguments);
});
});
return df;
}
}
var resolveFunc = function(type, status){
return function(context){
var args = this.resultArgs = (arguments.length > 1) ? arguments[1] : [];
return this.exec(context, this[type], args, status);
}
},
doneFunc = function(type, status){
return function(){
var self = this;
each(arguments, function( i, v, args ) {
if ( ! v )
return;
if ( v.constructor === Array ) {
args.callee.apply(self, v)
} else {
// immediately call the function if the deferred has been resolved
if (self.status === status)
v.apply(this, this.resultArgs || []);
self[type].push(v);
}
});
return this;
}
};
extend( Deferred.prototype, {
resolveWith : resolveFunc("doneFuncs","rs"),
rejectWith : resolveFunc("failFuncs","rj"),
done : doneFunc("doneFuncs","rs"),
fail : doneFunc("failFuncs","rj"),
always : function() {
var args = map(arguments);
if (args.length && args[0])
this.done(args[0]).fail(args[0]);
return this;
},
then : function() {
var args = map( arguments );
// fail function(s)
if (args.length > 1 && args[1])
this.fail(args[1]);
// done function(s)
if (args.length && args[0])
this.done(args[0]);
return this;
},
isResolved : function() {
return this.status === "rs";
},
isRejected : function() {
return this.status === "rj";
},
reject : function() {
return this.rejectWith(this, arguments);
},
resolve : function() {
return this.resolveWith(this, arguments);
},
exec : function(context, dst, args, st) {
if (this.status !== "")
return this;
this.status = st;
each(dst, function(i, d){
d.apply(context, args);
});
return this;
}
});
// HELPER METHODS FOR DEFERREDS
// Used to call a method on an object or resolve a
// deferred on it when a group of deferreds is resolved.
//
// whenEach(resources,"complete",resource,"execute")
var whenEach = function( arr, func, obj, func2 ) {
var deferreds = map(arr, func)
return Deferred.when.apply(Deferred, deferreds).then(function(){
if( isFn( obj[func2] )){
obj[func2]()
} else {
obj[func2].resolve();
}
})
},
// Used to call methods on multiple objects when
// a single deferred is resolved:
//
// whenThe(resource,"complete",resources,"load")
//
// TODO: this might be no longer used
whenThe = function( obj, func, items, func2 ) {
each(items, function(i, item){
Deferred.when(obj[func]).then(function() {
item[func2]();
})
})
};
// ## URI ##
/**
* @class steal.URI
* A URL / URI helper for getting information from a URL.
*
* var uri = URI( "http://stealjs.com/index.html" )
* uri.path //-> "/index.html"
*/
var URI = function( url ) {
if ( this.constructor !== URI ) {
return new URI( url );
}
extend(this, URI.parse( "" + url ));
}, root;
// the current url (relative to root, which is relative from page)
// normalize joins from this
//
extend( URI, {
/**
* Read or define the path relative URI's should be referenced from.
*
* window.location //-> "http://foo.com/site/index.html"
* steal.URI.root("http://foo.com/app/files/")
* steal.root.toString() //-> "../../app/files/"
*/
root : function(relativeURI){
if ( relativeURI !== undefined) {
root = URI(relativeURI);
// the current folder-location of the page http://foo.com/bar/card
var cleaned = URI.page,
// the absolute location or root
loc = cleaned.join(relativeURI);
// cur now points to the 'root' location, but from the page
URI.cur = loc.pathTo(cleaned)
steal.root = root;
return steal;
}
return root || URI("");
},
// parses a URI into it's basic parts
parse : function(string) {
var uriParts = string.split("?"),
uri = uriParts.shift(),
queryParts = uriParts.join("").split("#"),
protoParts = uri.split("://"),
parts = {
query : queryParts.shift(),
fragment : queryParts.join("#")
},
pathParts;
if ( protoParts[1] ) {
parts.protocol = protoParts.shift();
pathParts = protoParts[0].split("/");
parts.host = pathParts.shift();
parts.path = "/" + pathParts.join("/");
} else {
parts.path = protoParts[0];
}
return parts;
}
});
/**
* @attriute page
* The location of the page as a URI.
*
* steal.URI.page.protocol //-> "http"
*/
URI.page = URI( win.location && location.href );
/**
* @attribute cur
*
* The current working directory / path. Anything
* loaded relative will be loaded relative to this.
*/
URI.cur = URI();
/**
* @prototype
*/
extend( URI.prototype, {
dir : function(){
var parts = this.path.split("/");
parts.pop();
return URI(this.domain() + parts.join("/"))
},
filename : function(){
return this.path.split("/").pop();
},
ext : function(){
var filename = this.filename();
return ~ filename.indexOf(".") ? filename.split(".").pop() : "";
},
domain : function(){
return this.protocol ? this.protocol+"://"+this.host : "";
},
isCrossDomain : function( uri ) {
uri = URI( uri || win.location.href );
var domain = this.domain(),
uriDomain = uri.domain()
return (domain && uriDomain && domain != uriDomain) ||
this.protocol === "file" ||
( domain && !uriDomain );
},
isRelativeToDomain : function(){
return !this.path.indexOf("/");
},
hash : function(){
return this.fragment ? "#"+this.fragment : ""
},
search : function(){
return this.query ? "?"+this.query : ""
},
// like join, but returns a string
add : function(uri){
return this.join(uri)+'';
},
join : function(uri, min){
uri = URI(uri);
if ( uri.isCrossDomain( this )) {
return uri;
}
if ( uri.isRelativeToDomain() ) {
return URI( this.domain() + uri )
}
// at this point we either
// - have the same domain
// - this has a domain but uri does not
// - both don't have domains
var left = this.path ? this.path.split("/") : [],
right = uri.path.split("/"),
part = right[0];
//if we are joining from a folder like cookbook/, remove the last empty part
if ( this.path.match(/\/$/) ) {
left.pop();
}
while ( part == ".." && left.length) {
// if we've emptied out, folders, just break
// leaving any additional ../s
if(! left.pop() ){
break;
}
right.shift();
part = right[0];
}
return extend( URI( this.domain() + left.concat( right ).join("/") ), {
query: uri.query
});
},
/**
* For a given path, a given working directory, and file location, update the
* path so it points to a location relative to steal's root.
*
* We want everything relative to steal's root so the same app can work in
* multiple pages.
*
* ./files/a.js = steals a.js
* ./files/a = a/a.js
* files/a = //files/a/a.js
* files/a.js = loads //files/a.js
*/
normalize : function() {
var cur = URI.cur.dir(),
path = this.path;
//if path is rooted from steal's root (DEPRECATED)
if (!path.indexOf("//")) {
path = URI(path.substr(2));
} else if (!path.indexOf("./")) { // should be relative
path = cur.join( path.substr(2) );
}
// only if we start with ./ or have a /foo should we join from cur
else if (this.isRelative() ) {
path = cur.join(this.domain() + path)
}
path.query = this.query;
return path;
},
isRelative : function(){
return /^[\.|\/]/.test(this.path )
},
// a min path from 2 urls that share the same domain
pathTo : function( uri ) {
uri = URI(uri);
var uriParts = uri.path.split("/"),
thisParts = this.path.split("/"),
result = [];
while ( uriParts.length && thisParts.length && uriParts[0] == thisParts[0] ) {
uriParts.shift();
thisParts.shift();
}
each(thisParts, function(){ result.push("../") })
return URI(result.join("") + uriParts.join("/"));
},
mapJoin : function( url ) {
return this.join( URI( url ).insertMapping() );
},
// helper to go from jquery to jquery/jquery.js
addJS : function(){
var ext = this.ext();
if ( ! ext ) {
// if first character of path is a . or /, just load this file
if ( ! this.isRelative() ) {
this.path += "/" + this.filename();
}
this.path += ".js"
}
return this;
}
});
// This can't be added to the prototype using extend because
// then for some reason IE < 9 won't recognize it.
URI.prototype.toString = function(){
return this.domain()+this.path+this.search()+this.hash();
};
// temp add steal.File for backward compat
steal.File = steal.URI = URI;
// --- END URI
var pending = [],
s = steal,
id = 0;
/**
* @add steal
*/
// =============================== STATIC API ===============================
var page;
/**
* @static
*/
extend(steal, {
each : each,
extend : extend,
Deferred : Deferred,
isRhino: win.load && win.readUrl && win.readFile,
/**
* @attribute options
* Configurable options
*/
options : {
env : "development",
// TODO: document this
loadProduction : true,
needs : {
less: "steal/less/less.js",
coffee: "steal/coffee/coffee.js"
},
logLevel : 0
},
/**
* @hide
* when a 'unique' steal gets added ...
* @param {Object} stel
*/
add : function(stel){
steals[stel.rootSrc] = stel;
},
/**
* @hide
* Makes options
* @param {Object} options
*/
makeOptions : function(options){
// convert it to a uri
var src = options.src = URI(options.src);
if (!options.type) {
src = options.src = src.addJS();
}
var orig = src,
// path relative to the current files path
// this is done relative to jmvcroot
normalized = URI(orig).normalize();
extend(options, {
originalSrc : orig,
rootSrc : normalized,
// path from the page
src : URI.root().join( normalized )
});
options.originalSrc = options.src;
return options;
},
/**
* Calls steal, but waits until all previous steals
* have completed loading until loading the
* files passed to the arguments.
*/
then : function(){
return steal.apply( win, args);
},
/**
* Listens to events on Steal
* @param {String} event
* @param {Function} listener
*/
bind: function( event, listener ) {
if ( ! events[event] ) {
events[event] = []
}
var special = steal.events[event]
if ( special && special.add ) {
listener = special.add( listener );
}
listener && events[event].push( listener );
return steal;
},
one : function( event, listener ) {
return steal.bind(event,function(){
listener.apply(this, arguments);
steal.unbind(event, arguments.callee);
});
},
events : {},
/**
* Unbinds an event listener on steal
* @param {Object} event
* @param {Object} listener
*/
unbind : function(event, listener){
var evs = events[event] || [],
i = 0;
while ( i < evs.length ) {
if(listener === evs[i]){
evs.splice(i,1);
} else {
i++;
}
}
},
trigger : function(event, arg){
var arr = events[event] || [];
// array items might be removed during each iteration (with unbind),
// so we iterate over a copy
each( map( arr ), function(i,f){
f( arg );
})
},
/**
* @hide
* Used to tell steal that it is loading a number of plugins
*/
has: function() {
// we don't use IE's interactive script functionality while
// production scripts are loading
useInteractive = false;
each(arguments, function(i, arg) {
var stel = Resource.make( arg );
stel.loading = stel.executing = true;
});
},
// a dummy function to add things to after the stel is created, but before executed is called
preexecuted : function(){},
// called when a script has loaded via production
executed: function(name) {
// create the steal, mark it as loading, then as loaded
var stel = Resource.make( name );
stel.loading = true;
//convert(stel, "complete");
steal.preexecuted(stel);
stel.executed()
return steal;
},
/**
* Registers a type. You define the type of the file, the basic type it
* converts to, and a conversion function where you convert the original file
* to JS or CSS. This is modeled after the
* [http://api.jquery.com/extending-ajax/#Converters AJAX converters] in jQuery.
*
* Types are designed to make it simple to switch between steal's development
* and production modes. In development mode, the types are converted
* in the browser to allow devs to see changes as they work. When the app is
* built, these converter functions are run by the build process,
* and the processed text is inserted into the production script, optimized for
* performance.
*
* Here's an example converting files of type .foo to JavaScript. Foo is a
* fake language that saves global variables defined like. A .foo file might
* look like this:
*
* REQUIRED FOO
*
* To define this type, you'd call steal.type like this:
*
* steal.type("foo js", function(options, original, success, error){
* var parts = options.text.split(" ")
* options.text = parts[0]+"='"+parts[1]+"'";
* success();
* });
*
* The method we provide is called with the text of .foo files in options.text.
* We parse the file, create JavaScript and put it in options.text. Couldn't
* be simpler.
*
* Here's an example,
* converting [http://jashkenas.github.com/coffee-script/ coffeescript]
* to JavaScript:
*
* steal.type("coffee js", function(options, original, success, error){
* options.text = CoffeeScript.compile(options.text);
* success();
* });
*
* In this example, any time steal encounters a file with extension .coffee,
* it will call the given converter method. CoffeeScript.compile takes the
* text of the file, converts it from coffeescript to javascript, and saves
* the JavaScript text in options.text.
*
* Similarly, languages on top of CSS, like [http://lesscss.org/ LESS], can
* be converted to CSS:
*
* steal.type("less css", function(options, original, success, error){
* new (less.Parser)({
* optimization: less.optimization,
* paths: []
* }).parse(options.text, function (e, root) {
* options.text = root.toCSS();
* success();
* });
* });
*
* This simple type system could be used to convert any file type to be used
* in your JavaScript app. For example, [http://fdik.org/yml/ yml] could be
* used for configuration. jQueryMX uses steal.type to support JS templates,
* such as EJS, TMPL, and others.
*
* @param {String} type A string that defines the new type being defined and
* the type being converted to, separated by a space, like "coffee js".
*
* There can be more than two steps used in conversion, such as "ejs view js".
* This will define a method that converts .ejs files to .view files. There
* should be another converter for "view js" that makes this final conversion
* to JS.
*
* @param {Function} cb( options, original, success, error ) a callback
* function that converts the new file type to a basic type. This method
* needs to do two things: 1) save the text of the converted file in
* options.text and 2) call success() when the conversion is done (it can work
* asynchronously).
*
* - __options__ - the steal options for this file, including path information
* - __original__ - the original argument passed to steal, which might be a
* path or a function
* - __success__ - a method to call when the file is converted and processed
* successfully
* - __error__ - a method called if the conversion fails or the file doesn't
* exist
*/
type : function( type, cb ) {
var typs = type.split(" ");
if ( ! cb ) {
return types[typs.shift()].require
}
types[typs.shift()] = {
require : cb,
convert: typs
};
},
types : {}
});
// ============ RESOURCE ================
// a map of resources by resourceID
var resources = {};
// this is for methods on a 'steal instance'. A file can be in one of a few states:
// created - the steal instance is created, but we haven't started loading it yet
// this happens when thens are used
// loading - (loading=true) By calling load, this will tell steal to load a file
// loaded - (isLoaded=true) The file has been run, but its dependency files have been completed
// complete - all of this files dependencies have loaded and completed.
// A Resource is almost anything. It is different from a module
// as it doesn't represent some unit of functionality, rather
// it represents a unit that can have other units "within" it
// as dependencies. A resource can:
//
// - load - load the resource to the client so it is available, but don't run it yet
// - run - run the code for the resource
// - executed - the code has been run for the resource, but all
// dependencies for that resource might not have finished
// - completed - all resources within the resource have completed
//
// __options__
// `options` can be a string, function, or object.
//
// __properties__
//
// - options - has a number of properties
// - src - a URI to this resource that can be loaded from the current page
// - rootSrc - a URI to this resource relative to the current root URI.
// - type - the type of resource: "fn", "js", "css", etc
// - needs - other resources that must be loaded prior to this resource
// - fn - a callback function to run when executed
// - unique - false if this resource should be loaded each time
// - waits - this resource should wait until all prior scripts have completed before running
// - loaded - a deferred indicating if this resource has been loaded to the client
// - run - a deferred indicating if the the code for this resource run
// - completed - a deferred indicating if all of this resources dependencies have
// completed
// - dependencies - an array of dependencies
var Resource = function( options ) {
console.log("creating resource ... ",options)
// an array for dependencies, this is
this.dependencies = [];
// id for debugging
this.id = (++id);
// if we have no options, we are the global Resource that
// contains all other resources.
if ( ! options ) { //global init cur ...
this.options = {};
this.waits = false;
}
//handle callback functions
else if ( isFn( options )) {
var uri = URI.cur,
self = this,
cur = steal.cur;
this.options = {
fn : function() {
// Set the URI if there are steals
// within the callback.
URI.cur = uri;
// we should get the current "module"
// check it's listed dependencies and see
// if they have a value
var args = map(cur.dependencies, function(dep){
if(modules[dep.orig]){
return modules[dep.orig];
}
return dep.value;
})
var ret = options.apply(cur, args);
// if this returns a value, we should register it as a module ...
if(ret){
// register this module ....
cur.value = ret;
}
return ret;
},
rootSrc: uri,
orig: options,
type: "fn"
}
// this has nothing to do with 'loading' options
this.waits = true;
this.unique = false;
} else {
// save the original options
this.orig = options;
this.options = steal.makeOptions( extend({},
isString( options ) ? { src: options } : options ));
this.waits = this.options.waits || false;
this.unique = true;
}
//console.log("created", this.orig)
// create the deferreds used to manage state
this.loaded = Deferred();
this.run = Deferred();
this.completed = Deferred();
};
// `Resource.make` is used to either create
// a new resource, or return an existing
// resource that matches the options.
Resource.make = function( options ) {
// create the temporary reasource
var resource = new Resource( options ),
// use `rootSrc` as the definitive ID
rootSrc = resource.options.rootSrc;
// assuming this resource should not be created again.
if ( resource.unique && rootSrc ) {
// Check if we already have a resource for this rootSrc
// Also check with a .js ending because we defer 'type'
// determination until later
if ( ! resources[rootSrc] && ! resources[rootSrc + ".js"] ) {
// If we haven't loaded, cache the resource
resources[rootSrc] = resource;
} else {
// Otherwise get the cached resource
resource = resources[rootSrc];
// If options were passed, copy new properties over.
// Don't copy src, etc because those have already
// been changed to be the right values;
if(!isString( options )){
each(["src","rootSrc","originalSrc"], function(i, name){
delete options[name];
});
extend(resource.options, options);
}
}
}
return resource;
};
extend(Resource.prototype, {
// Calling complete indicates that all dependencies have
// been completed for this resource
complete : function(){
this.completed.resolve();
},
// After the script has been loaded and run
// - checks what has been stolen (in pending)
// - wires up pendings steal's deferreds to eventually complete this
// - this is where all of steal's complexity is
executed: function( script ) {
var myqueue,
stel,
src = ( script && script.src) || this.options.src,
rootSrc = this.options.rootSrc;
// Set this as the current file so any relative urls
// will load from it.
if ( this.options.rootSrc ) {
URI.cur = URI( rootSrc );
}
// set this as the current resource
steal.cur = this;
// mark yourself as 'loaded'.
this.run.resolve();
// If we are IE, get the queue from interactives.
// It in interactives because you can't use onload to know
// which script is executing.
if (support.interactive && src) {
myqueue = interactives[src];
}
// In other browsers, the queue of items to load is
// what is in pending
console.log(this.orig, "queue= ", pending.slice(0))
if ( ! myqueue ) {
myqueue = pending.slice(0);
pending = [];
}