On Wed, Sep 1, 2010 at 09:07, Tranninger Harald <[email protected]>wrote:
>
>
> Now I made another mechanism like this:
>
>
>
> func2
>
> *var* iconarray = *this*.dbdatainstance.getIconArray();
>
> *for* (*var* i=0; i < iconarray.getLength(); i++)
>
> {
>
> *var* icon = iconarray.getItem(i);
>
> *var* button = icon.getButton();
>
>
>
> button.addListener("dblclick", *function*(e) {
>
> *if*(cws.Application.loginvalue == *true*){
>
> *this*.moveObject(desktop, icon);
>
> }
>
> },*this*);
>
> }
>
>
>
> All buttons are restored on the desktop so far, with all the right
> properties out of the Db. The now problem is, that
>
> Somehow always the last listener is on every button! So If I want to move
> any button, always the last one is moved!
>
>
>
> I don´t know why this doesn´t happen in func1 ! I know that trough
> iteration the icon is always the last, but why isn´t that also in func1 so?
>
JavaScript does not have block-level scoping. All variable declarations
anyplace in a function are effectively moved to the top of the function.
Your icon variable used in the loop is the same variable in every instance
of your listener function, so it has the value it was last assigned. You
don't, anyplace, store the current value to create a closure that is unique
to a particular loop iteration.
Closures are an interesting beast, and are not available in most traditional
languages so seem strange. Once you get used to them they're really useful,
but until you do, they seem to act strangely. This was why I recommended,
for the time being, using the setUserData() method of widgets.
In this case, you can most easily solve the problem by creating a closure on
"this" (it appears to be a container, so let's call it "container") and
passing "icon" as the context to the listener function:
*var* iconarray = *this*.dbdatainstance.getIconArray();
var container = this; // Store the context which will be used in the
listener
*for* (*var* i=0; i < iconarray.getLength(); i++)
{
*var* icon = iconarray.getItem(i);
*var* button = icon.getButton();
button.addListener("dblclick", *function*(e) {
*if*(cws.Application.loginvalue == *true*){
*container*.moveObject(desktop, this); // note
"this" is the icon here
}
},*icon*); // pass icon as the context
}
Derrell
------------------------------------------------------------------------------
This SF.net Dev2Dev email is sponsored by:
Show off your parallel programming skills.
Enter the Intel(R) Threading Challenge 2010.
http://p.sf.net/sfu/intel-thread-sfd
_______________________________________________
qooxdoo-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/qooxdoo-devel