-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.js
283 lines (253 loc) · 11.1 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
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
//
// Atto Core : helper functions and such (AMD)
//
// author: Ryan Corradini
// date: 31 Oct 2012
// license: MIT
//
// polyfill classList if necessary (seriously, IE9? Seriously?!?)
// source: http://purl.eligrey.com/github/classList.js/blob/master/classList.js
if(typeof document!=="undefined"&&!("classList" in document.createElement("a"))){(function(j){var a="classList",f="prototype",m=(j.HTMLElement||j.Element)[f],b=Object,k=String[f].trim||function(){return this.replace(/^\s+|\s+$/g,"")},c=Array[f].indexOf||function(q){var p=0,o=this.length;for(;p<o;p++){if(p in this&&this[p]===q){return p}}return -1},n=function(o,p){this.name=o;this.code=DOMException[o];this.message=p},g=function(p,o){if(o===""){throw new n("SYNTAX_ERR","An invalid or illegal string was specified")}if(/\s/.test(o)){throw new n("INVALID_CHARACTER_ERR","String contains an invalid character")}return c.call(p,o)},d=function(s){var r=k.call(s.className),q=r?r.split(/\s+/):[],p=0,o=q.length;for(;p<o;p++){this.push(q[p])}this._updateClassName=function(){s.className=this.toString()}},e=d[f]=[],i=function(){return new d(this)};n[f]=Error[f];e.item=function(o){return this[o]||null};e.contains=function(o){o+="";return g(this,o)!==-1};e.add=function(o){o+="";if(g(this,o)===-1){this.push(o);this._updateClassName()}};e.remove=function(p){p+="";var o=g(this,p);if(o!==-1){this.splice(o,1);this._updateClassName()}};e.toggle=function(o){o+="";if(g(this,o)===-1){this.add(o)}else{this.remove(o)}};e.toString=function(){return this.join(" ")};if(b.defineProperty){var l={get:i,enumerable:true,configurable:true};try{b.defineProperty(m,a,l)}catch(h){if(h.number===-2146823252){l.enumerable=false;b.defineProperty(m,a,l)}}}else{if(b[f].__defineGetter__){m.__defineGetter__(a,i)}}}(self))};
define(
function() {
var _head = document.getElementsByTagName('head')[0] || {};
function _xhr(args) {
var opts = _args_mixin({
url: '',
postData: '',
success: null,
failure: null,
accept: null,
form: null
}, args);
var req = _createXMLHTTPObject();
if (!req) return;
if (opts.postData || opts.form) {
req.open('POST', opts.url, true);
req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
} else {
req.open('GET', opts.url, true);
}
if (opts.accept) {
var acceptMIMEType = null;
switch (opts.accept) {
case 'html':
acceptMIMEType = 'text/html';
break;
case 'json':
acceptMIMEType = 'application/json';
break;
default:
break;
}
if (acceptMIMEType) req.setRequestHeader('Accept', acceptMIMEType);
}
req.onreadystatechange = function () {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
//alert('HTTP error ' + req.status);
if (opts.failure && typeof opts.failure === 'function') {
//console.debug(opts.failure);
opts.failure.call(this,req);
}
return;
}
if (opts.success && typeof opts.success === 'function') {
opts.success.call(this, req.response || req.responseText);
}
}
if (req.readyState == 4) return;
if (opts.form) {
if (typeof opts.form == 'string') opts.form = document.getElementById(opts.form);
opts.postData = _serializeForm(opts.form);
}
req.send(opts.postData);
}
var _XMLHttpFactories = [
function () {return new XMLHttpRequest()},
function () {return new ActiveXObject("Msxml2.XMLHTTP")},
function () {return new ActiveXObject("Msxml3.XMLHTTP")},
function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];
function _createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0; i < _XMLHttpFactories.length; i++) {
try {
xmlhttp = _XMLHttpFactories[i]();
}
catch (e) {
continue;
}
break;
}
return xmlhttp;
}
function _serializeForm(theForm) {
var i, args = [], formElements = theForm.childNodes;
for (i=0; i<formElements.length; i++) {
if (formElements[i].name) {
args.push( formElements[i].name + "=" + encodeURIComponent(formElements[i].value) );
}
}
return args.join('&');
}
function _isArray(it) {
// shamelessly lifted from Dojo Base)
return it && (it instanceof Array || typeof it === "array");
}
function _colonSplit(s) {
return s ? s.split(':') : null;
}
function _parse_args(arglist) {
var args = [];
if (arglist) {
if (typeof arglist === 'string') {
args = arglist.split(',').map(String.trim).map(_colonSplit); // split by comma, trim whitespace, then split by colon
} else if (_isArray(arglist)) {
args = arglist.map(_colonSplit);
} else if (typeof arglist === 'object') {
for (var k in arglist) {
args.push([k, arglist[k]]);
}
}
}
return args;
}
function _args_mixin(old_args, new_arglist) {
var new_args = _parse_args(new_arglist), key, val;
for (var i in new_args) {
key = new_args[i][0];
val = new_args[i][1];
old_args[key] = val;
}
return old_args;
} // --> this is the one that gets exposed
function _deepExtend(destination, source) {
for (var property in source) {
if (source[property] && source[property].constructor &&
source[property].constructor === Object) {
console.log('recursing ', property);
destination[property] = destination[property] || {};
arguments.callee(destination[property], source[property]);
} else {
console.log('copying ', property);
destination[property] = source[property];
}
}
return destination;
};
function _isObjectLiteral(o) {
return o && o.constructor && o.constructor.name === 'Object';
}
function _stopEventCascade(e) {
if (!e) var e = window.event || {};
if (e.preventDefault) {
e.preventDefault();
} else if (e.stop) {
e.stop();
} else {
e.cancelBubble = true;
}
e.returnValue = false;
if (e.stopPropagation) e.stopPropagation();
}
function _addLoadEvent(func) {
/*
Simon Willison's unobtrusive onLoad event handler
(http://simonwillison.net/2004/May/26/addLoadEvent/)
Example usage:
atto.addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
atto.addLoadEvent(function() {
// more code to run on page load
});
*/
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function _addEvent(tgt, type, func, useCapture) {
// follows the API of the standard addEventListener, but abstracts it to work cross-browser
var capture = useCapture || false;
if (tgt.addEventListener) {
// modern standards-based browsers
tgt.addEventListener(type, func, capture);
} else if (tgt.attachEvent) {
// IE < 9
tgt.attachEvent('on'+type, func);
} else if (typeof tgt['on'+type] !== 'undefined') {
// old school (can assign to the element's event handler this way, provided it's not undefined)
var oldfunc = tgt['on'+type];
if (typeof oldfunc === 'function') {
tgt['on'+type] = function() { oldfunc(); func(); };
} else {
tgt['on'+type] = func;
}
} else {
alert ("Can't add this event type: " + type + " to this element: " + tgt);
}
}
function _byId(id) {
// convenience shortcut; no real improvement other than code shorthand
return document.getElementById(id);
}
function _supplant(str, args) {
/*
adapted from Douglas Crockford's Remedial JavaScript
Example usage:
alert(atto.supplant("I'm {age} years old!", { age: 29 }));
alert(atto.supplant("The {a} says {n}, {n}, {n}!", { a: 'cow', n: 'moo' }));
*/
return str.replace(/{([^{}]*)}/g,
function (a, b) {
var r = args[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
}
function _addWidgetCss(rawCss, forWidget) {
var ss = document.createElement('style');
ss.setAttribute('data-for-widget', forWidget);
ss.setAttribute('type', 'text/css');
_head.appendChild(ss);
if (ss.styleSheet) {
// stupid versions of IE
ss.styleSheet.cssText = rawCss;
} else {
// everyone else
ss.appendChild(document.createTextNode(rawCss));
}
}
function _getKeys(obj) {
var k, keylist = [];
for (k in obj) {
if (obj.hasOwnProperty(k)) {
keylist.push(k);
}
}
return keylist;
}
return {
addLoadEvent : _addLoadEvent,
addEvent : _addEvent,
addWidgetCss : _addWidgetCss,
byId : _byId,
isArray : _isArray,
stopEventCascade : _stopEventCascade,
xhrRequest : _xhr,
mixinArgs : _args_mixin,
extend : _args_mixin,
deepExtend : _deepExtend,
supplant : _supplant,
head : _head,
getKeys : _getKeys
}
}
);