So this question follows on from my previous question Under what conditions does a Knockout native template re-render
After some investigation, it seems that if a template defines an afterRender function and that afterRender function references a part model then, if that part of the model is subsequently altered, the afterRender function is called again.
This behaviour seems similar to computedObservables (aka dependentObservables) where knockout tracks which parts of the model it depends on and then re-runs the computedObservables whenever one of the values it depends on changes.
To demonstrate this I have written a jsFiddle: http://jsfiddle.net/unklefolk/nczCt/1/
As expected the afterRender function is called when the view is rendered. However, if you click the checkbox, the afterRender function is run again as it uses viewModel.selectedPet().pet().IsHappy()
This does not make sense to me. So my question is:
- Is this a bug that the
afterRenderfunction is being re-run? - How can I ensure that the
afterRenderfunction is only run once?
Thanks in advance.
Knockout uses a computed observable to wrap the execution of the bindings on an element. This is how the bindings are triggered again when a dependency changes (this link might help explain further.
Currently, the
afterRendercode is not excluded from adding to these dependencies. If this is not desirable for your scenario, then there are a couple of ways to prevent it.setTimeout: like http://jsfiddle.net/rniemeyer/nczCt/2/peekfunction on observables that allows you to get the value without creating a dependency.