>       for( var i=0; i< labels.length; i++) 
>       {
>         var label = new qx.ui.basic.Label(labels[i]);
>         this.addListener("my-special-event",function(row,label){ 
>           return function(e){
>                 if( e.getData() == row ) {
>                   label.setBackgroundColor( "white" );  
>                 }
>                 else {
>                   label.resetBackgroundColor();
>                 }
>               }
>         }(i,label)); // to get the variables into the closure
>         grid.add( label, { row : i, column : 0 } );
>       }

I was half-way aware that Javascript closures close over variable
references, not values. This can be tricky, as you wrote, but also handy
at times. The trick you showed is to *evaluate* the variable of interest
(here by passing it as a parameter to a function call), and creating the
desired closure in the scope of the called function, where it now closes
over the wrapping function which is fresh with every iteration through
the loop. So each returned listener function effectively gets its own
scope it closes over. (Of course they all also close over the binding of
the outer functions like the one that contains the for loop, but those
bindings are not relevant here. - I think there is a name for this
technique, but I can't remember :).

Now, you also passed an object reference, label, to the wrapper
function. What if that variable didn't change, but the object it points
to?! E.g.

  var label = new qx.ui.basic.Label();
  for ( var i=0; i< labels.length; i++)
  {
    label.setValue(labels[i]);
    // ... (continue as above
  }

All listeners would share the same label instance, and after the loop it
would have the last labels string as its value property :-). So its
really important that the variable you pass into the wrapper function
actually changes with every loop iteration (and not only the value it
refers to).

T.

------------------------------------------------------------------------------
Start uncovering the many advantages of virtual appliances
and start using them to simplify application deployment and
accelerate your shift to cloud computing.
http://p.sf.net/sfu/novell-sfdev2dev
_______________________________________________
qooxdoo-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/qooxdoo-devel

Reply via email to