-
Notifications
You must be signed in to change notification settings - Fork 1
/
core.js
75 lines (72 loc) · 2.51 KB
/
core.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
var jojo = MojoJojo = {
version: "0.1",
/**
* Simple incremental ID provider for cases where the developer wants to rely on the framework to auto ID stuff
*/
id: (function() {
var currID = 0;
return function() {
return "jojo" + currID++;
};
})(),
/**
* Namespacing function, derived from: http://higher-order.blogspot.com/2008/02/designing-clientserver-web-applications.html
* - added robust support for defining namespaces on arbitrary contexts (defaults to window)
* - added the fact that it returns the new namespace object regardless of the context
* @param {Object} spec - the namespace string or spec object (ex: {com: {trifork: ['model,view']}})
* @param {Object} context - the root context onto which the new namespace is added (defaults to window)
*/
ns: function(spec, context) {
var validIdentifier = /^(?:[a-zA-Z_]\w*[.])*[a-zA-Z_]\w*$/,i,N;
context = context || window;
spec = spec.valueOf();
var ret;
if (typeof spec === 'object') {
if (typeof spec.length === 'number') {//assume an array-like object
for (i=0,N=spec.length;i<N;i++) {
ret = jojo.ns(spec[i],context);
}
}
else {//spec is a specification object e.g, {com: {trifork: ['model,view']}}
for (i in spec) if (spec.hasOwnProperty(i)) {
context[i] = context[i] || {};
ret = jojo.ns(spec[i], context[i]);//recursively descend tree
}
}
} else if (typeof spec === 'string') {
ret = (function handleStringCase(){
var parts;
if (!validIdentifier.test(spec)) {
throw new Error('"'+spec+'" is not a valid name for a package.');
}
parts = spec.split('.');
for (i=0,N=parts.length;i<N;i++) {
spec = parts[i];
context[spec] = context[spec] || {};
context = context[spec];
}
return context; // return the lowest object in the hierarchy
})();
}
else {
throw new Error("jojo.ns() requires a valid namespace spec to be passed as the first argument");
}
return ret;
},
/**
* Flyweight empty Function
*/
emptyFn: function() {},
/**
* Flyweight empty Object
*/
emptyObj: {},
/**
* Flyweight empty String
*/
emptyString: "",
/**
* Flyweight empty Array
*/
emptyArray: []
};