This repository has been archived by the owner on May 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Namespace.js
500 lines (453 loc) · 13.4 KB
/
Namespace.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
/*
Script: Namespace.js
Namespace utility
Copyright:
Copyright (c) 2009 Maxime Bouroumeau-Fuseau
License:
MIT-style license.
Version:
1.1
*/
/*jslint evil : true */
/*global Namespace, XMLHttpRequest, ActiveXObject, window, document */
var Namespace = (function() {
var _listeners = {};
var _includedIdentifiers = [];
/**
* Returns an object in an array unless the object is an array
*
* @param mixed obj
* @return Array
*/
var _toArray = function(obj) {
// checks if it's an array
if (typeof(obj) == 'object' && obj.sort) {
return obj;
}
return Array(obj);
};
/**
* Creates an XMLHttpRequest object
*
* @return XMLHttpRequest
*/
var _createXmlHttpRequest = function() {
var xhr;
try { xhr = new XMLHttpRequest(); } catch(e) {
try { xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e2) {
try { xhr = new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e3) {
try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e4) {
try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e5) {
throw new Error( "This browser does not support XMLHttpRequest." );
}
}
}
}
}
return xhr;
};
/**
* Checks if an http request is successful based on its status code.
* Borrowed from dojo (http://www.dojotoolkit.org).
*
* @param Integer status Http status code
* @return Boolean
*/
var _isHttpRequestSuccessful = function(status) {
return (status >= 200 && status < 300) || // Boolean
status == 304 || // allow any 2XX response code
status == 1223 || // get it out of the cache
(!status && (window.location.protocol == "file:" || window.location.protocol == "chrome:") ); // Internet Explorer mangled the status code
};
/**
* Creates a script tag with the specified data as content
*
* @param String data The content of the script
*/
var _createScript = function(data) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.text = data;
if (typeof window.execScript === "object") { // According to IE
window.execScript(data);
} else {
try { // Attempt body insertion
document.body.appendChild(script);
} catch (e) { // Fall back on eval
window['eval'](data);
}
}
};
/**
* Dispatches an event
*
* @param String eventName
* @param Object properties
*/
var _dispatchEvent = function(eventName, properties) {
if (!_listeners[eventName]) { return; }
properties.event = eventName;
for (var i = 0; i < _listeners[eventName].length; i++) {
_listeners[eventName][i](properties);
}
};
/**
* Creates an Object following the specified namespace identifier.
*
* @public
* @param String identifier The namespace string
* @param Object klasses (OPTIONAL) An object which properties will be added to the namespace
* @return Object The most inner object
*/
var _namespace = function(identifier) {
var klasses = arguments[1] || false;
var ns = window;
if (identifier !== '') {
var parts = identifier.split(Namespace.separator);
for (var i = 0; i < parts.length; i++) {
if (!ns[parts[i]]) {
ns[parts[i]] = {};
}
ns = ns[parts[i]];
}
}
if (klasses) {
for (var klass in klasses) {
if (klasses.hasOwnProperty(klass)) {
ns[klass] = klasses[klass];
}
}
}
_dispatchEvent('create', { 'identifier': identifier });
return ns;
};
/**
* Checks if the specified identifier is defined
*
* @public
* @param String identifier The namespace string
* @return Boolean
*/
_namespace.exist = function(identifier) {
if (identifier === '') { return true; }
var parts = identifier.split(Namespace.separator);
var ns = window;
for (var i = 0; i < parts.length; i++) {
if (!ns[parts[i]]) {
return false;
}
ns = ns[parts[i]];
}
return true;
};
/**
* Maps an identifier to a uri. Is public so it can be overriden by custom scripts.
*
* @public
* @param String identifier The namespace identifier
* @return String The uri
*/
_namespace.mapIdentifierToUri = function(identifier) {
var regexp = new RegExp('\\' + Namespace.separator, 'g');
return Namespace.baseUri + identifier.replace(regexp, '/') + '.js';
};
/**
* Loads a remote script atfer mapping the identifier to an uri
*
* @param String identifier The namespace identifier
* @param Function successCallback When set, the file will be loaded asynchronously. Will be called when the file is loaded
* @param Function errorCallback Callback to be called when an error occurs
* @return Boolean Success of failure when loading synchronously
*/
var _loadScript = function(identifier) {
var successCallback = arguments[1];
var errorCallback = arguments[2];
var async = typeof successCallback === "function";
var uri = _namespace.mapIdentifierToUri(identifier);
var event = { 'identifier': identifier, 'uri': uri, 'async': async, 'callback': successCallback };
var xhr = _createXmlHttpRequest();
xhr.open("GET", uri, async);
if (async) {
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (_isHttpRequestSuccessful(xhr.status || 0)) {
_createScript(xhr.responseText);
_dispatchEvent('include', event);
successCallback();
return;
}
event.status = xhr.status;
_dispatchEvent('includeError', event);
if (typeof errorCallback === "function") {
errorCallback();
}
}
};
}
xhr.send(null);
if (!async) {
if (_isHttpRequestSuccessful(xhr.status || 0)) {
_createScript(xhr.responseText);
_dispatchEvent('include', event);
return true;
}
event.status = xhr.status;
_dispatchEvent('includeError', event);
return false;
}
};
/**
* Includes a remote javascript file identified by the specified namespace string. The identifier
* must point to a class. Separators in the string will be converted to slashes and the .js extension will be appended.
*
* @public
* @param String identifier The namespace string
* @param Function callback (OPTIONAL) A function to call when the remote script has been included
*/
_namespace.include = function(identifier) {
var successCallback = arguments[1] || false;
var errorCallback = arguments[2] || false;
// checks if the identifier is not already included
if (_includedIdentifiers[identifier]) {
if (typeof successCallback === "function") { successCallback(); }
return true;
}
if (successCallback) {
_loadScript(identifier, function() {
_includedIdentifiers[identifier] = true;
successCallback();
}, errorCallback);
} else {
if (_loadScript(identifier)) {
_includedIdentifiers[identifier] = true;
return true;
}
return false;
}
};
/**
* Imports properties from the specified namespace to the global space (ie. under window)
*
* The identifier string can contain the * wildcard character as its last segment (eg: com.test.*)
* which will import all properties from the namespace.
*
* If not, the targeted namespace will be imported (ie. if com.test is imported, the test object
* will now be global). If the targeted object is not found, it will be included using include().
*
* @public
* @param String identifier The namespace string
* @param Function callback (OPTIONAL) A function to call when the process is completed (including the include() if used)
* @param Boolean autoInclude (OPTIONAL) Whether to automatically auto include the targeted object is not found. Default is Namespace.autoInclude
*/
_namespace.use = function(identifier) {
var identifiers = _toArray(identifier);
var callback = arguments[1] || false;
var autoInclude = arguments.length > 2 ? arguments[2] : Namespace.autoInclude;
var event = { 'identifier': identifier };
var parts, target, ns;
for (var i = 0; i < identifiers.length; i++) {
identifier = identifiers[i];
parts = identifier.split(Namespace.separator);
target = parts.pop();
ns = _namespace(parts.join(Namespace.separator));
if (target == '*') {
// imports all objects from the identifier, can't use include() in that case
for (var objectName in ns) {
if (ns.hasOwnProperty(objectName)) {
window[objectName] = ns[objectName];
}
}
} else {
// imports only one object
if (ns[target]) {
// the object exists, import it
window[target] = ns[target];
} else {
// the object does not exist
if (autoInclude) {
// try to auto include it
if (callback) {
_namespace.include(identifier, function() {
window[target] = ns[target];
if (i + 1 < identifiers.length) {
// we continue to unpack the rest from here
_namespace.unpack(identifiers.slice(i + 1), callback, autoInclude);
} else {
// no more identifiers to unpack
_dispatchEvent('use', event);
if (typeof callback === "function") {
callback();
}
}
});
return;
} else {
_namespace.include(identifier);
window[target] = ns[target];
}
}
}
}
}
// all identifiers have been unpacked
_dispatchEvent('use', event);
if (typeof callback === "function") { callback(); }
};
/**
* Binds the include() and unpack() method to a specified identifier
*
* @public
* @param String identifier The namespace identifier
* @return Object
*/
_namespace.from = function(identifier) {
return {
/**
* Includes the identifier specified in from()
*
* @see Namespace.include()
*/
include: function() {
var callback = arguments[0] || false;
_namespace.include(identifier, callback);
},
/**
* Includes the identifier specified in from() and unpack
* the specified indentifier in _identifier
*
* @see Namespace.use()
*/
use: function(_identifier) {
var callback = arguments[1] || false;
if (_identifier.charAt(0) == '.') {
_identifier = identifier + _identifier;
}
if (callback) {
_namespace.include(identifier, function() {
_namespace.use(_identifier, callback, false);
});
} else {
_namespace.include(identifier);
_namespace.use(_identifier, callback, false);
}
}
};
};
/**
* Registers a namespace so it won't be included
*
* Idea and code submitted by Nathan Smith (http://github.com/smith)
*
* @param String|Array identifier
*/
_namespace.provide = function(identifier) {
var identifiers = _toArray(identifier);
for (var i = 0; i < identifiers.length; i++) {
if (!(identifier in _includedIdentifiers)) {
_dispatchEvent('provide', { 'identifier': identifier });
_includedIdentifiers[identifier] = true;
}
}
};
/**
* Registers a function to be called when the specified event is dispatched
*
* @param String eventName
* @param Function callback
*/
_namespace.addEventListener = function(eventName, callback) {
if (!_listeners[eventName]) { _listeners[eventName] = []; }
_listeners[eventName].push(callback);
};
/**
* Unregisters an event listener
*
* @param String eventName
* @param Function callback
*/
_namespace.removeEventListener = function(eventName, callback) {
if (!_listeners[eventName]) { return; }
for (var i = 0; i < _listeners[eventName].length; i++) {
if (_listeners[eventName][i] == callback) {
delete _listeners[eventName][i];
return;
}
}
};
/**
* Adds methods to javascript native's object
* Inspired by http://thinkweb2.com/projects/prototype/namespacing-made-easy/
*
* @public
*/
_namespace.registerNativeExtensions = function() {
/**
* @see Namespace()
*/
String.prototype.namespace = function() {
var klasses = arguments[0] || {};
return _namespace(this.valueOf(), klasses);
};
/**
* @see Namespace.include()
*/
String.prototype.include = function() {
var callback = arguments[0] || false;
return _namespace.include(this.valueOf(), callback);
};
/**
* @see Namespace.use()
*/
String.prototype.use = function() {
var callback = arguments[0] || false;
return _namespace.use(this.valueOf(), callback);
};
/**
* @see Namespace.from()
*/
String.prototype.from = function() {
return _namespace.from(this.valueOf());
};
/**
* @see Namespace.provide()
* Idea and code submitted by Nathan Smith (http://github.com/smith)
*/
String.prototype.provide = function() {
return _namespace.provide(this.valueOf());
};
/**
* @see Namespace.use()
*/
Array.prototype.use = function() {
var callback = arguments[0] || false;
return _namespace.use(this, callback);
};
/**
* @see Namespace.provide()
*/
Array.prototype.provide = function() {
return _namespace.provide(this);
};
};
return _namespace;
})();
/**
* Namespace segment separator
*
* @var String
*/
Namespace.separator = '.';
/**
* Base uri when using Namespace.include()
* Must end with a slash
*
* @var String
*/
Namespace.baseUri = './';
/**
* Whether to automatically call Namespace.include() when Namespace.import()
* does not find the targeted object.
*
* @var Boolean
*/
Namespace.autoInclude = true;