JSON compatible with Ry Dahl's Ajax.Pull + example
[upr.git] / examples / rails_app-2.3.4 / public / javascripts / ajax_pull / ajax_pull.js
blob8b0236dbc0c602b5463ba14217ae849acfc667ea
1 // ref: http://rubyforge.org/pipermail/mongrel-users/2007-July/003747.html
2 // ry dahl <ry@tinyclouds.org>
3 // Don't Poll. Pull!
4 // version 0.1
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();
15 this.request(url);
16 this.startPuller();
19 startPuller: function() {
20 this.pullPointer = 0;
21 this.puller = new PeriodicalExecuter(this.pull.bind(this), this.frequency);
24 pull: function() {
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;
41 }).bind(this));
45 });
48 Object.extend(String.prototype, {
49 extractJSON: function() {
50 var insideString = false;
51 var sBrackets = cBrackets = parens = 0;
52 var statements = new Array();
53 var start = i = 0;
54 for(i = 0; i < this.length; i++) {
55 if( cBrackets < 0 || sBrackets < 0 || parens < 0 ) {
56 // raise syntax error?
58 if(insideString) {
59 switch(this[i]) {
60 case '\\': i++; break;
61 case '"': insideString = false; break;
63 } else {
64 switch(this[i]) {
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;
72 case ';':
73 if(cBrackets == 0 && sBrackets == 0 && parens == 0) {
74 statements.push(this.slice(start, i));
75 start = i+1;
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));
83 return statements;
85 });