I'm preferring this way instead of closures:

for( var key in data )
{
 var button = new qx.ui.form.Button( data[key].label );
 button.setUserData("id", key);
 vbox.add(button);

 button.addListener("execute",function(ev){
   alert("Bad:" + data[ev.getTarget().getUserData("id")].label);
 },this);
}

Not tested, maybe there is bug in code, but logically is should be ok.

2009/10/26 Derrell Lipman <[email protected]>:
> On Sun, Oct 25, 2009 at 20:39, panyasan <[email protected]> wrote:
>>
>> What I am trying to achieve is to get a local variable ('key') that is the
>> product of the iteration through the keys of an object into a closure
>> (here:
>> an event listener). The problem is that when the event listener is called,
>> the variable "key" evaluates to the last value it had when the iteration
>> was
>> completed, not to the value it had when the even listener was created. The
>> only solution I could come up after a lot of experimenting was to use an
>> ugly eval. Does anyone have a better idea?
>
> var vbox = new qx.ui.container.Composite( new qx.ui.layout.VBox(5));
> this.getRoot().add(vbox);
> var data = {
>  "one": { label: "One" },
>  "two" : { label: "Two" },
>  "three":{ label: "Three" },
>  "four":{ label: "Four" },
>  "five":{ label: "Five" }
> };
>
> for( var key in data )
> {
>  var button = new qx.ui.form.Button( data[key].label );
>  vbox.add(button);
>
>  // this doesn't work
>  button.addListener("execute",function(){
>    alert("Bad:" + data[key].label);
>  },this);
>
>  (function()
>   {
>     var thisKey = key;
>     button.addListener("execute", function(){
>       alert("Good:" + data[thisKey].label);
>     },this);
>   })();
> }
>
> ------------------------------------------------------------------------------
> Come build with us! The BlackBerry(R) Developer Conference in SF, CA
> is the only developer event you need to attend this year. Jumpstart your
> developing skills, take BlackBerry mobile applications to market and stay
> ahead of the curve. Join us from November 9 - 12, 2009. Register now!
> http://p.sf.net/sfu/devconference
> _______________________________________________
> qooxdoo-devel mailing list
> [email protected]
> https://lists.sourceforge.net/lists/listinfo/qooxdoo-devel
>
>



-- 
Best regards
- Petr Kobalicek <http://kobalicek.com>

------------------------------------------------------------------------------
Come build with us! The BlackBerry(R) Developer Conference in SF, CA
is the only developer event you need to attend this year. Jumpstart your
developing skills, take BlackBerry mobile applications to market and stay 
ahead of the curve. Join us from November 9 - 12, 2009. Register now!
http://p.sf.net/sfu/devconference
_______________________________________________
qooxdoo-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/qooxdoo-devel

Reply via email to