19

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?

Can Gencer
  • 8,822
  • 5
  • 33
  • 52
  • I've given up on progressive enhancement with Knockout. Beyond anything *super-trivial* it is just not practical to keep the non-KO/KO behavior synchronized .. this is an issue with even standard JavaScript PE, but the rich binding model of KO makes it an *extreme divergence* in approaches. (Maybe there is a "Server-side KO" project? That would be .. interesting to say the least.) – user2864740 Nov 16 '13 at 06:50

5 Answers5

4

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.

Can Gencer
  • 8,822
  • 5
  • 33
  • 52
  • +1 I have arrived at the same conclusion - without full server-side support for KO (a new project, anyone?), it's just too divergent of an approach from a traditional HTML/postback model to practically keep synchronized. – user2864740 Nov 16 '13 at 06:58
3

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.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
3

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.

Tomasz Zieliński
  • 16,136
  • 7
  • 59
  • 83
  • 1
    I pretty much came to the same conclusion, unfortunately. Maybe it will be improved in a future version of Knockout (i.e. through some way to bind to existing dom elements). – Can Gencer Jan 28 '12 at 13:30
  • Tomasz, curious how you render server side - are you using node? rhino? something else? Overall, curious if you have managed to use the same templates server side as on the client, or if you have to maintain two sets of templates. – Karl Rosaen Jun 19 '12 at 17:37
  • @Karl: The backend was Django, so templates looked like this:
    {{ my_data }}
    – Tomasz Zieliński Jun 19 '12 at 22:44
  • gotcha thanks. was thinking of experimenting with rhino, though the bindings ko code probably has a lot of dom de – Karl Rosaen Jun 20 '12 at 03:01
1

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());
        }
    }
};
SavoryBytes
  • 35,571
  • 4
  • 52
  • 61
0

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.

Tyson Cadenhead
  • 352
  • 3
  • 8
  • Here is an example of how you could loop over a bunch of items on the server and then re-draw them in a Knockout foreach loop: http://www.tysoncadenhead.com/blog/using-knockout-for-progressive-enhancement-on-lists – Tyson Cadenhead Jul 28 '14 at 14:23