Let's say we have data as follows
var data = {
facets: [{
name : "some name",
values: [{
value: "some value"
}]
}]
};
We can easily represent this as a view model bound to a knockout template as follows:
<ul data-bind="foreach: facets">
<li>
<span data-bind="text: name"></span>
<ul data-bind="foreach: values">
<li data-bind="text: value"></li>
</ul>
</li>
</ul>
The question is, how can we achieve the same result when using progressive enhancement? That is by having the template render on the server side initially and then binding the knockout template and the view model to that rendering.
A simple server side template would look something like this:
<ul>
<li>
<span>some name</span>
<ul>
<li>some value</li>
</ul>
</li>
</ul>
I have explored a few different possibilities:
One is create one knockout template and one server side template, and generate the Knockout view model dynamically by parsing the DOM for the server side template. In this way, only the Knockout template would be visible when JavaScript is enabled, and only the server side template would be visible if JavaScript is disabled. They could be styled in a way to make them look identical.
Another approach is to apply bindings for each item in the facets array seperately to the existing DOM element for that facet. However this is still only one level deep and does not work for the nested elements.
Neither of these approaches seem rather clean. Another solution might be to write a custom binding that handles the whole rendering and reuses existing elements if possible.
Any other ideas?