[clug] javascript jquery and long calls

Kevin Pulo kev at pulo.com.au
Wed Mar 30 17:26:13 MDT 2011


Like Neill, I also don't fully understand this stuff.  But I was
recently pointed to this document

https://github.com/spencertipping/js-in-ten-minutes/raw/master/js-in-ten-minutes.pdf

Section 3.3 suggests that as Neill says, you're probably seeing this
strangeness because 'this' isn't a variable, and it takes different
values in different circumstances.

My (poor) understanding of JS's closures is that a function
(particularly anonymous ones) can "see" the local variables of the
function that it's defined inside of.  In the jquery code I'm
currently playing with, I have code along the lines of the below, and
it seems to work okay.

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

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

I'm not sure how the argument passing might affect things (ie. if
they're passed by value, not reference) - in my code the call to
$.ajax is done directly in the scope of the variables that the success
function refers to.

Also not sure how the setTimeout would affect things.  You'll probably
be better off with something like

    setTimeout(function(){waitForMessage(url, textout);}, 1000);

since then the scoping and variable references are more likely to work
out.

Kev

-- 
Kevin Pulo
kev at pulo.com.au
http://www.kev.pulo.com.au/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
URL: <http://lists.samba.org/pipermail/linux/attachments/20110331/03f5336d/attachment.pgp>


More information about the linux mailing list