I've been trying to learn more about DynamicModule (I do not use them, as I used Manipulate all the time).
After some time struggling with this, and reading everything I can about Dynamics, and lots of trials and errors, I gave up.
Any one can figure why this DynamicModule will initialize correctly and run ok, ONLY after I hit ENTER on the cell an extra time?
This is a problem, since when I saved it to a CDF and opened the CDF, it does not run, since it needs an ENTER to initialize, which is not possible to do in CDF.
DynamicModule[{max = Pi/4, plot = plotClass[Pi/4]},
Row[{
Dynamic[plot@set[max]],
Framed@Grid[{
{Slider[Dynamic[max], {.1, 2 Pi, .1}], Dynamic@max},
{Dynamic[plot@make[]], SpanFromLeft}
}
]
}
],
Initialization :> {
plotClass[$max_] := Module[{self, mymax},
self@set[v_] := mymax = v;
self@make[] := Module[{x},
Plot[Sin[x], {x, 0, mymax}, PlotRange -> {{0, 2 Pi}, {-1, 1}},
ImageSize -> 200]
];
mymax = $max;
self
]
}
]

To see the problem, simply do
- Paste the above into an empty cell (but do not hit ENTER yet)
- close the kernel
Evalution->Quit kernel - Hit ENTER on the cell. Now you'll see the plot
- Now move the slider. You'll see that the plot does not update
- Now hit ENTER one more time into the cell. Now moving the slider will update the plot
- To reproduce, delete the output cell and go back to step 2.
So it needs one more ENTER to work. Another way to see this, is to save the notebook as CDF and open the CDF. You'll see it does not work.
I am sure I am doing something silly. But as I said, I just started learning DynamicModule.
The problem is with the evaluation with the Module in the Initialization section. It does not get defined without an extra ENTER for some reason. I tried many different way to define this Module, and they are failed. One extra ENTER is needed.
Mathematica 9.0.1, on windows 7.

When DynamicModule is first evaluated, initial assignments for local variables are made during the evaluation. Any setting for the Initialization option is evaluated only when the output of DynamicModule is displayed.So, as the docs already stated earlier, variables are localized and initialized, the body is evaluated. It will be displayed after that. That's when the Initialization code will execute. – Sjoerd C. de Vries Feb 24 '13 at 13:03plot: During the kernel-evaluationplotwill be localized, with a naming likeplot$9944. Then when it is displayed, the FrontEnd takes over the control about variables local toDynamicModuleandplotgets yet another name, something like FE'plot$$137. I don't think that this means you are using a global variable anywhere, though. – Albert Retey Feb 24 '13 at 16:22