-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathjquery.ev.js
98 lines (91 loc) · 2.21 KB
/
jquery.ev.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* Title: jQuery.ev
*
* A COMET event loop for jQuery
*
* $.ev.loop long-polls on a URL and expects to get an array of JSON-encoded
* objects back. Each of these objects should represent a message from the COMET
* server that's telling your client-side Javascript to do something.
*
*/
(function($){
$.ev = {
handlers : {},
running : false,
xhr : null,
verbose : true,
timeout : null,
/* Method: run
*
* Respond to an array of messages using the object in this.handlers
*
*/
run: function(messages) {
var i, m, h; // index, event, handler
for (i = 0; i < messages.length; i++) {
m = messages[i];
if (!m) continue;
h = this.handlers[m.type];
if (!h) h = this.handlers['*'];
if ( h) h(m);
}
},
/* Method: stop
*
* Stop the loop
*
*/
stop: function() {
if (this.xhr) {
this.xhr.abort();
this.xhr = null;
}
this.running = false;
},
/*
* Method: loop
*
* Long poll on a URL
*
* Arguments:
*
* url
* handler
*
*/
loop: function(url, handlers) {
var self = this;
if (handlers) {
if (typeof handlers == "object") {
this.handlers = handlers;
} else if (typeof handlers == "function") {
this.run = handlers;
} else {
throw("handlers must be an object or function");
}
}
this.running = true;
this.xhr = $.ajax({
type : 'GET',
dataType : 'json',
cache : false,
url : url,
timeout : self.timeout,
success : function(messages, status) {
// console.log('success', messages);
self.run(messages)
},
complete : function(xhr, status) {
var delay;
if (status == 'success') {
delay = 100;
} else {
// console.log('status: ' + status, '; waiting before long-polling again...');
delay = 5000;
}
// "recursively" loop
window.setTimeout(function(){ if (self.running) self.loop(url); }, delay);
}
});
}
};
})(jQuery);