messenger.js
1.97 KB
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
define([], function() {
var listeners = [];
var messenger = {
process: function() {
var url = "/comet/messenger"
var request = new XMLHttpRequest();
var responseLength = 0;
request.open("GET", url, true);
request.setRequestHeader("Content-Type","application/x-javascript;");
request.onreadystatechange = function() {
if (request.readyState == 3 || request.readyState == 4) {
if (request.status == 200){
if (request.responseText) {
var newText = request.responseText.substr(responseLength);
if (newText.length > 0) {
for (var i=0; i < listeners.length; i++) {
listeners[i](newText);
}
}
responseLength = request.responseText.length;
}
}
if (request.readyState == 4) {
// Request is complete. Remove existing callback.
request.onreadystatechange = null;
if (request.status == 200) {
setTimeout(function() { messenger.process(); }, 500);
} else {
console.log('Error, retrying in 5 seconds');
setTimeout(function() { messenger.process(); }, 5000);
}
}
}
};
request.send(null);
},
addListener: function(listener) {
listeners.push(listener);
},
removeListener: function(listener) {
var index = listeners.indexOf(listener);
if (index > -1) {
array.splice(index, 1);
}
}
}
messenger.process();
return messenger;
});