Updated solution
Here is another way that works. It is perhaps to be preferred to the other two from a programming style point of view. In the OP, the function buildButton
depends on external variables. It would be better to pass these variables to the function. In this case, since the variables are to be altered, the symbols need to be passed to the function unevaluated. Given the context I would choose to wrap the variables in Dynamic
, in the manner of controls. The definition of buildButton
may appear inside or outside the DynamicModule
. It makes no difference, in fact.
buildButton[idx_, Dynamic[tab_], Dynamic[button_]] := Button["xx", tab = 2; button = idx];
DynamicModule[{tabClicked, buttonClicked},
TabView[{
"First" ->
Dynamic@Grid[{{buildButton[1, Dynamic[tabClicked], Dynamic[buttonClicked]],
buildButton[2, Dynamic[tabClicked], Dynamic[buttonClicked]]}}],
"Second" -> Dynamic[buttonClicked]}, Dynamic[tabClicked]]
]
Original solutions
Two solutions:
Put buildButton
in the DynamicModule
:
DynamicModule[{tabClicked, buttonClicked, buildButton},
buildButton[idx_] := Button["xx", tabClicked = 2; buttonClicked = idx];
TabView[{"First" -> Dynamic@Grid[{{buildButton[1], buildButton[2]}}],
"Second" -> Dynamic[buttonClicked]}, Dynamic[tabClicked]]]
Or change DynamicModule
to Module
Module[{tabClicked, buttonClicked},
buildButton[idx_] := Button["xx", tabClicked = 2; buttonClicked = idx];
TabView[{"First" -> Dynamic@Grid[{{buildButton[1], buildButton[2]}}],
"Second" -> Dynamic[buttonClicked]}, Dynamic[tabClicked]]]
It has to do with when the symbols get processed by the front end from something like $CellContext`buttonClicked$$
to FE`buttonClicked$$26
, I think. If they don't get the same number after the $$
, they are really different variables.
Edit update:
It seems in the OP's code the variables tabClicked
and buttonClicked
get assigned symbols like tabClicked$44774
and buttonClicked$44774
, while the variables in the TabView
get assigned symbols like FE`tabClicked$$26
and FE`buttonClicked$$26
. However, I have been unable to figure out why this happens. A halfway guess is that the definition of buildButton
happens in the kernel, and tabClicked$44774
etc. look like Module
symbols instead of DynamicModule
symbols (e.g. FE`tabClicked$$26
). This is what led me to suggest putting buildButton
in the list of DynamicModule
variables, by the way.
TabView[{1, 2}]
? $\endgroup$