forked from gonzalo123/nov-comet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNovComet.js
executable file
·74 lines (65 loc) · 2.05 KB
/
NovComet.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
/**
* Lazy Comet. JS client (publisher and subscriber)
*
* THIS PROGRAM COMES WITH ABSOLUTELY NO WARANTIES !
* USE IT AT YOUR OWN RISKS !
*
* @author Gonzalo Ayuso <[email protected]>
* @copyright under GPL 2 licence
*/
NovComet = {
sleepTime: 1000,
_subscribed: {},
_timeout: undefined,
_baseurl: "comet.php",
_args: '',
_urlParam: 'subscribed',
subscribe: function(id, callback) {
NovComet._subscribed[id] = {
cbk: callback,
timestamp: NovComet._getCurrentTimestamp()
};
return NovComet;
},
_refresh: function() {
NovComet._timeout = setTimeout(function() {
NovComet.run()
}, NovComet.sleepTime);
},
init: function(baseurl) {
if (baseurl!=undefined) {
NovComet._baseurl = baseurl;
}
},
_getCurrentTimestamp: function() {
return Math.round(new Date().getTime() / 1000);
},
run: function() {
var cometCheckUrl = NovComet._baseurl + '?' + NovComet._args;
for (var id in NovComet._subscribed) {
var currentTimestamp = NovComet._subscribed[id]['timestamp'];
cometCheckUrl += '&' + NovComet._urlParam+ '[' + id + ']=' +
currentTimestamp;
}
cometCheckUrl += '&' + NovComet._getCurrentTimestamp();
$.getJSON(cometCheckUrl, function(data){
switch(data.s) {
case 0: // sin cambios
NovComet._refresh();
break;
case 1: // trigger
for (var id in data['k']) {
NovComet._subscribed[id]['timestamp'] = data['k'][id];
NovComet._subscribed[id].cbk(data.k);
}
NovComet._refresh();
break;
}
});
},
publish: function(id) {
var cometPublishUrl = NovComet._baseurl + '?' + NovComet._args;
cometPublishUrl += '&publish=' + id;
$.getJSON(cometPublishUrl);
}
};