Question

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?

Was it helpful?

Solution

I explored several approaches here, including generating an anonymous template from the first element, as described here:

http://groups.google.com/group/knockoutjs/browse_thread/thread/3896a640583763d7

or creating seperate bindings for each element of the array through a custom binding, such as

ko.bindingHandlers.prerenderedArray = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
        var binding = valueAccessor();              
        binding.firstTime = true;

        $(element).children().each(function(index, node) {                  
            var value = ko.utils.unwrapObservable(binding.value)[index];                        
            ko.applyBindings(value, node);
        }); 

        return { 'controlsDescendantBindings': true };              
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {             
        var binding = valueAccessor();
        if (binding.firstTime) {
            binding.firstTime = false;
            return;
        }               

        $(element).children().remove(); 
        ko.applyBindingsToNode(element, { template: { name: binding.template, foreach: binding.value }}, viewModel)
    }
};      

which applies a specific binding to each element and then on the first update replaces the contents with an ordinary foreach binding. This approach still means you still need to have two templates. Both of these also involve initializing the state through a JSON rendered by the server.

The current approach I chose to use (still subject to change, though) is to put all the Knockout templates inside script tags so that they never get rendered in NoJS browsers. The NoJS templates are rendered as contents of a div on the server side. As soon as the Knockout template gets rendered, the contents of the div will be replace by the Knockout template in the script tags. You can style them in identical / similar ways to make the transition seamless, and if this is not possible hide the noJS template through CSS.

In the end, I came to the conclusion that Knockout.js and progressive enhancement don't really work very well together, one should pick either the other, i.e. build some parts of the application that require progressive enhancement using more traditional methods such direct jQuery DOM manipulation.

OTHER TIPS

Just add the various data-attributes in the server-side templates. They don't hurt if JavaScript is disabled so having them is not a problem at all.

I'm afraid there is no clean way of doing that. Personally I render the page in the backend and then I pass the very same context data to the frontend (serialized as JSON) and set up Knockout using it. This means that there is some duplication. Maybe switching the backend to node.js would simplify things here.

Here's my take on it, this basic example uses a custom binding to load the server side values into the view model.

Progressive Enhancement with KnockoutJS Infinite Scroll

screenshot

Progressive enhancement binding

ko.bindingHandlers.PE = {
    init: function(element, valueAccessor, allBindings) {
        var bindings = allBindings();
        if (typeof bindings.text === 'function') {
            bindings.text($(element).text());
        }
    }
};

here, I suggested a template binding that uses the generated HTML from the server. It usage i similar to the original Template binding, except for the few data-attributes that will be used by the binding.

Progressive enhancement is much easier with non-looping data like forms (as I wrote about here: http://www.tysoncadenhead.com/blog/using-knockout-for-progressive-enhancement ). Personally, I think that looping over multiple items in the DOM and re-rendering them seems like it would be a tough implementation, but it's hard to think of anything better.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top