1 // ref: http://rubyforge.org/pipermail/mongrel-users/2007-July/003747.html
2 // ry dahl <ry@tinyclouds.org>
5 Ajax
.Pull
= Class
.create();
7 Ajax
.Pull
.prototype = Object
.extend(Ajax
.Request
.prototype, {
8 initialize: function(url
, options
) {
9 this.handler
= options
.handler
;
10 this.frequency
= options
.frequency
|| 0.5;
11 options
['method'] = options
['method'] || 'get';
12 this.setOptions(options
);
13 this.transport
= Ajax
.getTransport();
19 startPuller: function() {
21 this.puller
= new PeriodicalExecuter(this.pull
.bind(this), this.frequency
);
25 if(this.transport
.readyState
< 3) {
26 return; // not receiving yet
27 } else if (this._complete
) {
28 this.puller
.stop(); // this is our last pull
31 var slice
= this.transport
.responseText
.slice(this.pullPointer
);
33 (this.options
.pullDebugger
|| Prototype
.emptyFunction
)(
34 'slice: <code>' + slice
+ '</code>');
36 slice
.extractJSON().each((function(statement
) {
37 (this.options
.pullDebugger
|| Prototype
.emptyFunction
)(
38 'extracted statement: <code>' + statement
+ '</code>');
39 this.handler(eval( '(' + statement
+ ')' ));
40 this.pullPointer
+= statement
.length
+ 1;
48 Object
.extend(String
.prototype, {
49 extractJSON: function() {
50 var insideString
= false;
51 var sBrackets
= cBrackets
= parens
= 0;
52 var statements
= new Array();
54 for(i
= 0; i
< this.length
; i
++) {
55 if( cBrackets
< 0 || sBrackets
< 0 || parens
< 0 ) {
56 // raise syntax error?
60 case '\\': i
++; break;
61 case '"': insideString
= false; break;
65 case '"': insideString
= true; break;
66 case '{': cBrackets
++; break;
67 case '}': cBrackets
--; break;
68 case '[': sBrackets
++; break;
69 case ']': sBrackets
--; break;
70 case '(': parens
++; break;
71 case ')': parens
++; break;
73 if(cBrackets
== 0 && sBrackets
== 0 && parens
== 0) {
74 statements
.push(this.slice(start
, i
));
79 // if the last statement doesn't have a semicolon, it's okay
80 // if(i != start && cBrackets == 0 && sBrackets == 0 && parens == 0)
81 // statements.push(this.slice(start));