Is there any possibility to get extra information about the Figure, which was clicked, when dealing with an onMouseDown event? I mean, extra variables that can be included when the Figure was constructed. This, to be used in a list comprehension. Like, for example, when constructing a Treemap.
The OnMouseDown event takes a closure as a parameter, which in principle can capture any variable of the scope in which is was created.
Here is the example code from the documentation at http://tutor.rascal-mpl.org/Rascal/Libraries/Vis/Figure/Properties/onMouseDown/onMouseDown.html, extended with "extra information":
import vis::KeySym;
s = "";
s2 = "";
extraInformation = "some additional info about the b box"; // definition of extra information
b = box(text(str () { return s; }),
fillColor("red"),
onMouseDown(bool (int butnr, map[KeyModifier,bool] modifiers) {
s = "<butnr>" + extraInformation; // later use of extra information
return true;
}));
It is important to understand that the closure/lambda captures bindings to the variables, not their values. So the contents of the extraInformation
variable changes if some other code which captures the same variable changes it. In the example, this happens for the s
variable, but not for the extraInformation
variable because nobody assigns into it after the initial declaration.
So, watch out for binding loop variables from for
loops and comprehensions: they always end up having the contents of the final loop iteration. To work around this, introduce an extra variable like so:
boxes = [box(..., onMouseDown(..., bool (int butnr, map[KeyModifier,bool] modifiers) { use of var })) | x <- elements, var := x];
or like so:
boxes = for (x <- elements) {
var = x;
append box(..., onMouseDown(..., bool (int butnr, map[KeyModifier,bool] modifiers) { use of var }));
}
If we would have used x
instead of var
in the closure all your boxes would have the same value for x
, which is the last element of elements
. W