Hello,
this is a JavaScript question, but one that I bump into once in a while when
developing with qooxdoo.
Test the following code in the playground:
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);
// this works but is a nasty hack
eval('button.addListener("execute",function(){'+
'alert("Good:"+data["'+ key+ '"].label);'+
'},this);');
}
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?
Thanks,
Christian
--
View this message in context:
http://n2.nabble.com/Getting-an-iterated-local-variable-into-a-closure-tp3889573p3889573.html
Sent from the qooxdoo mailing list archive at Nabble.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