forked from markmarijnissen/cordova-app-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pegasus.js
44 lines (35 loc) · 1.17 KB
/
pegasus.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
// Retrieved and slightly modified from: https://github.com/typicode/pegasus
// --------------------------------------------------------------------------
//
// a url (naming it a, beacause it will be reused to store callbacks)
// xhr placeholder to avoid using var, not to be used
function pegasus(a, xhr) {
xhr = new XMLHttpRequest();
// Open url
xhr.open('GET', a);
// Reuse a to store callbacks
a = [];
// onSuccess handler
// onError handler
// cb placeholder to avoid using var, should not be used
xhr.onreadystatechange = xhr.then = function(onSuccess, onError, cb) {
// Test if onSuccess is a function or a load event
if (onSuccess.call) a = [,onSuccess, onError];
// Test if request is complete
if (xhr.readyState == 4) {
// index will be:
// 0 if undefined
// 1 if status is between 200 and 399
// 2 if status is over
cb = a[0|xhr.status / 200];
// Safari doesn't support xhr.responseType = 'json'
// so the response is parsed
if (cb) cb(xhr.status === 200?JSON.parse(xhr.responseText):xhr);
}
};
// Send
xhr.send();
// Return request
return xhr;
}
module.exports = pegasus;