Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Progressive Enhancement with KnockoutJS

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?

like image 553
Can Gencer Avatar asked Jan 22 '12 12:01

Can Gencer


People also ask

What is KnockoutJS used for?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.

How do you activate a KnockoutJS model?

Activating Knockout But since the browser doesn't know what it means, you need to activate Knockout to make it take effect. To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel);

Is knockout JS Mvvm?

Yes, knockout. js does apply the MVVM pattern. It's explained in the documentation: A model: your application's stored data.

What is $data in knockout?

The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.


1 Answers

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.

like image 186
Can Gencer Avatar answered Nov 15 '22 16:11

Can Gencer