Take the following example for hiding/showing a notebook through a Checkbox:
x = True;
CreateDocument[{"hello"}, Visible -> Dynamic[x]];
Checkbox[Dynamic[x]]
It works correctly until the kernel is restarted, but not after.
The documentation explains that the variables in a DynamicModule are owned by the front end, not the kernel. So to make this piece of GUI resistant to kernel quits/crashes, I tried:
DynamicModule[
{x = True},
CreateDocument[{"hello"}, Visible -> Dynamic[x]];
Checkbox[Dynamic[x]]
]
This one does not work though. Can someone explain why, and whether there is to use this DynamicModule variable outside the DynamicModule? Is this behaviour somehow related to the DynamicModuleParent option?
Update: As Brett Champion has pointed out in the comments below, there's a similar example in the documentation in the DynamicModule Wormholes section. This shows how to make it possible to access a particular DynamicModule's variable from another DynamicModule using the InheritScope -> True setting. However, my example I don't have a second DynamicModule in the newly created notebook, only a single Dynamic, so I am not sure how to connect the variables.
Answer
What you want to do (make this piece of GUI resistant to kernel quits) can be achieved simply like this:
DynamicModule[
{x = True, tag = Unique[StringJoin["g", ToString[
$SessionID]]]}, CreateDocument[{"hello"},
TaggingRules -> tag, Visible -> True];
Checkbox[Dynamic[x,
(x = #1; TrueQ[Select[Notebooks[],
CurrentValue[#1, TaggingRules] === tag & ] /.
{b_NotebookObject} :> (CurrentValue[b,
Visible] = ! CurrentValue[b,
Visible])]) & ]]]
The "wormhole" is a unique identitfier attached to TaggingRules.
Comments
Post a Comment