[Greasemonkey] Silly JavaScript question

John Plsek gm at plsek.id.au
Thu Jul 21 07:54:54 EDT 2005


Dan Phiffer wrote:

> Hey guys,
>
> Sorry to interrupt the bigger discussion with a mundane, perhaps OT,  
> JavaScript question. I've looked around a bit and I'm not sure how  
> exactly to search my way to a solution.
>
> Say I'm iterating over some object or array like so:
>
> for (prop in something) {
>     ...
> }
>
> Then within that block I want to call a GM_xmlhttpRequest with a  
> callback closure:
>
> for (prop in something) {
>     GM_xmlhttpRequest({
>         ...
>         onload: function() {
>             switch (prop) {
>                  ...
>             }
>         }
>     }
> }
>
> I've found that whatever the last value of prop is ends up being  
> applied to each callback, since they're just referencing a variable  
> that gets reset on each iteration. That is to say if something is  
> {'one': 1, 'two': 2}, the result would be two calls where prop is set  
> to 'two'. Is there a clean way to pass information along to the  
> onload function? I like the way setTimeout handles this (e.g.  
> setTimeout(function(foo) { alert(foo); }, 0, 'yo');).
>
> Thanks,
> -Dan
> _______________________________________________
> Greasemonkey mailing list
> Greasemonkey at mozdev.org
> http://mozdev.org/mailman/listinfo/greasemonkey
>
>
I'm sure I'll be given a million reasons why this is wrong, but it works 
for me,
for (prop in something) {
    GM_xmlhttpRequest({
        prop:prop;                // added this bit
        ...
        onload: function() {
            switch (this.prop) {  // changed this bit
                 ...
            }
        }
    }
}

John


More information about the Greasemonkey mailing list