-
Notifications
You must be signed in to change notification settings - Fork 5
/
MediawikiJS.js
76 lines (72 loc) · 2.4 KB
/
MediawikiJS.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
(function () {'use strict';
/**
* @static
* @private
*/
var JSONP = (function (global) {
// (C) WebReflection Essential - Mit Style
// cleaned up by Brett Zamir for JSLint and avoiding additional globals and need for conventional [?&]callback= in URL)
// 'use strict'; // Added above
var id = 0,
ns = 'MediaWikiJS',
prefix = '__JSONP__',
document = global.document,
documentElement = document.documentElement;
return function (uri, callback) {
var src = prefix + id++,
script = document.createElement('script'),
JSONPResponse = function () {
try { delete global[ns][src]; } catch(e) { global[ns][src] = null; }
documentElement.removeChild(script);
callback.apply(this, arguments);
};
global[ns][src] = JSONPResponse;
documentElement.insertBefore(
script,
documentElement.lastChild
).src = uri + (uri.indexOf('?') > -1 ? '&' : '?') + 'callback=' + ns + '.' + src;
};
}(window));
/**
* @constructor
* @param {object|string} opts The options (currently "baseURL" and "apiPath" args only); if a string is supplied, it will be used as the baseURL
* @param {object} argObj Object of key-value pairs to be serialized
* @param {function} cb The callback to execute upon server (JSONP) reply
*/
function MediaWikiJS(opts, argObj, cb) {
if (!(this instanceof MediaWikiJS)) {
return new MediaWikiJS(opts, argObj, cb);
}
if (typeof opts === 'string') {
this.baseURL = opts;
}
else {
this.apiPath = opts.apiPath;
this.baseURL = opts.baseURL;
}
if (!this.apiPath) {
this.apiPath = '/w/api.php';
}
if (argObj) {
this.send(argObj, cb);
}
}
/**
* Send the API request to the server
* @param {object} argObj Object of arguments to be serialized
* @param {function} cb The callback to execute upon server (JSONP) reply
*/
MediaWikiJS.prototype.send = function MediaWikiJS__send (argObj, cb) {
cb = cb || function () {}; // Are there API calls with side effects?
var uri, arg, args = '';
for (arg in argObj) {
if (argObj.hasOwnProperty(arg)) {
args += '&' + arg + '=' + encodeURIComponent(argObj[arg]);
}
}
uri = this.baseURL + this.apiPath + '?format=json' + args;
JSONP(uri, cb);
};
// EXPORTS
window.MediaWikiJS = MediaWikiJS;
}());