messenger.js
2.6 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
define([], function() {
var channels = {};
var messenger = {
process: function() {
var self = this;
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) {
self.deliver(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);
},
deliver: function(newText) {
try {
var json = JSON.parse(newText);
if (json.channel && channels[json.channel]) {
for (var i=0; i < channels[json.channel].length; i++) {
channels[json.channel][i](json);
}
}
} catch (err) {
console.log('Error processing COMETd message', newText, err);
}
},
addListener: function(listener) {
this.addListener('ALL', listener);
},
addListener: function(channel, listener) {
if (!channels[channel]) {
channels[channel] = [];
}
channels[channel].push(listener);
},
removeListener: function(listener) {
this.removeListener('ALL', listener);
},
removeListener: function(channel, listener) {
console.log('Remove listener from channel', listener, channel);
}
}
messenger.process();
return messenger;
});