问题
I have a complex knockout page that renders a template conditionally:
<!-- ko template: {'if': $root.itemToEdit.SomeObject() === $data, name: 'EditItemTemplate', afterRender: $root.initializeEditPanel } -->
<!-- /ko -->
and the template:
<script type="text/html" id="EditItemTemplate">
<div id="editContainer" class="fd_editContainer">
//.. lots of markup and knockout bindings ...
<input class="checkbox" id="questionDisplayOptionOverride" type="checkbox" data-bind="checked: $data.AnObject().ItemText.HasOverrideText" />
//.. lots of markup and knockout bindings ...
</div>
</script>
Here is what is confusing me. There are a bunch elements in the markup that alter properties on the $data
object. These do not cause the template to re-render. However, for some reason, when a certain checkbox is clicked (questionDisplayOptionOverride
) the full template is re-rendered and my afterRender
function $root.initializeEditPanel
is called. I do not know why this is happening as the questionDisplayOptionOverride
control only alters a computedObservable
property inside the $data
object, not the actual $data
object itself.
So my question:
Under what conditions would a template completely re-render?
Clearly if the template condition 'if': $root.itemToEdit.SomeObject() === $data
changed the template would re-render but are there any other conditions under which this would happen?
Due to the complexity of my page a jsFiddle is not an option. I am more interested in the general mechanism that causes templates to re-render.
Edit: See The afterRender template call seems to be executed as a computedObservables. Why and how to fix it? as a follow up question to this.
回答1:
The template in your case would re-render whenever $root.itemToEdit.SomeObject
changed. If it contains an object, then it is not good enough for just one of its properties to be changed. The entire observable needs to be updated for notifications to happen.
That is the only way that your template would get re-rendered except for something like getting re-rendered because of a parent template.
来源:https://stackoverflow.com/questions/11241540/under-what-conditions-does-a-knockout-native-template-re-render