-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
56 lines (45 loc) · 1.56 KB
/
index.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
var EventEmitter = require('events').EventEmitter;
var oldOpen = window.XMLHttpRequest.prototype.open;
module.exports = function (onrequest) {
function open () {
var emitter = new EventEmitter();
var xhr = this;
emitter.method = arguments[0];
emitter.url = arguments[1];
emitter.xhr = xhr;
onrequest(emitter);
xhr.addEventListener('readystatechange', onreadystatechange.bind(xhr));
xhr.addEventListener('abort', onabort.bind(xhr));
xhr.addEventListener('error', onerror.bind(xhr));
xhr.addEventListener('timeout', ontimeout.bind(xhr));
oldOpen.apply(xhr, arguments);
function removeListeners (xhrInstance) {
xhrInstance.removeEventListener('readystatechange', onreadystatechange);
xhrInstance.removeEventListener('abort', onabort);
xhrInstance.removeEventListener('error', onerror);
xhrInstance.removeEventListener('timeout', onabort);
}
function onreadystatechange (e) {
if (xhr.readyState === window.XMLHttpRequest.OPENED) {
return emitter.emit('open', xhr);
}
if (xhr.readyState === window.XMLHttpRequest.DONE && xhr.status) {
removeListeners(xhr);
return emitter.emit('done', xhr);
}
}
function onabort (e) {
removeListeners(xhr);
return emitter.emit('abort', xhr);
}
function onerror (e) {
removeListeners(xhr);
return emitter.emit('error', xhr);
}
function ontimeout (e) {
removeListeners(xhr);
return emitter.emit('timeout', xhr);
}
}
window.XMLHttpRequest.prototype.open = open;
};