Progressive Enhancement with KnockoutJS
Asked Answered
B

5

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?

Bibeau answered 22/1, 2012 at 12:34 Comment(1)
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.)Bodrogi
B
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.

Bibeau answered 28/1, 2012 at 13:29 Comment(1)
+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.Bodrogi
L
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.

Lepley answered 22/1, 2012 at 12:35 Comment(2)
That works only if you have a flat data structure, how would you handle arrays and nested arrays?Bibeau
Yeah, also adding and removing lines from tables, that sort of thing.Childhood
C
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.

Chloramine answered 22/1, 2012 at 13:45 Comment(4)
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).Bibeau
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.Fixture
@Karl: The backend was Django, so templates looked like this: <div data-bind="text: my_data">{{ my_data }}</div>Goer
gotcha thanks. was thinking of experimenting with rhino, though the bindings ko code probably has a lot of dom deFixture
S
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());
        }
    }
};
Salonika answered 26/9, 2014 at 19:58 Comment(0)
P
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.

Permissible answered 23/7, 2014 at 18:33 Comment(1)
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: tysoncadenhead.com/blog/…Permissible

© 2022 - 2024 — McMap. All rights reserved.