[clug] javascript jquery and long calls

jm jeffm at ghostgun.com
Tue Mar 29 23:35:00 MDT 2011


I'm experimenting with comet a  the moment using jquery. The problem I'm 
having is the variable 'this' doesn't appear to be in scope. What I'm
trying to do in set up an object which stores various bits of 
information, eg this.url should be the URL to call and this.textout 
should be the div to write the messages to, this object has the method 
waitForMessage() as defined below. The expected behaviour is that I call 
it once, makes a call to the remote url, then falls through while 
waiting due to async being true, it then appends the returned text to 
the div, and calls itself.

function bar() {
     this.setup = setup;
     this.waitForMessage = waitForMessage;
}

function setup(url, textout) {
   this.url = url;
   this.textout = textout;
   this.waitForMessage();
}

function waitForMessage() {
     $.ajax({
             url: this.url,
                 async: true,
                 cache: false,
                 success: function(data){
                 if (data.text) {
                     for(var i = 0; i < data.text.length; i++) {
                         this.textout.append($(data.text[i]));
                     }
                 }
                 setTimeout('waitForMessage()', 1000);
             }
         });
}

Can anyone tell me how this SHOULD be written?


Jeff.




More information about the linux mailing list