On Fri, May 17, 2013 at 11:04 AM, fei wang <wang...@romeo-foxtrot.com>wrote:

> Hi,
>
> the follow is my snipplet code:
>
> //----------------------------------------------------------------
> __arr : ['A', 'B', 'C', 'D', 'E', 'F'],
>
> fillData : function() {
>     for(var k=0; k<this.arr.length; k++) {
>      var args = ...
>      var req = new qx.io.request.Xhr("/hrm/services/ActionServlet2",
> "POST");
> req.setRequestData({
>  'class' : 'InternalDAO',
> 'method' : 'queryCommentAndScore',
> 'async' : false,
>  'args' : args
> });
>       req.addListener("success", function(e) {
>                         console.log("k=" + k); // Here, the value is
> always '6', why?
>                         // BUT, My intention is to print 0, 1, 2, 3, 4, 5.
> How shoud I do?
>  }, this);
>
> req.send();
> }
>
> }
>

Your loop quickly sends out six requests, adds a listener function which
will be called when the Xhr response is returned, and then returns to the
browser. The final value of k, before returning to the browser and before
any instance of your listener function was called, is 6. The "closures"
that allow each of the listener functions to access that now-out-of-scope
variable, k, therefore each have that final value of k before it went out
of scope: 6.

This is a very common problem encountered by people new to JavaScript.
There are various ways to solve the problem. JavaScript does not provide
block-level scope, so there is no pretty way to do it. Here's one solution
(untested):

function getNewListener(index)
{
return function(e)
 {
console.log("k=" + index);
};
}

req.addListener("success", getNewListener(k), this);


Here, the getNewListener() function is called with each value of k, and so
each call instance has an index parameter which is used in the returned
function. Since each index parameter is unique, the closure has a unique
value to print in console.log.

Read up on closures. It's a key aspect of JavaScript, and very confusing,
initially.

Cheers,

Derrell
------------------------------------------------------------------------------
AlienVault Unified Security Management (USM) platform delivers complete
security visibility with the essential security capabilities. Easily and
efficiently configure, manage, and operate all of your security controls
from a single console and one unified framework. Download a free trial.
http://p.sf.net/sfu/alienvault_d2d
_______________________________________________
qooxdoo-devel mailing list
qooxdoo-devel@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/qooxdoo-devel

Reply via email to