Dynamic templates with knockout


Staff member
I have a viewmodel whose template I want to change dynamically at runtime when the state of my application changes. I referred to this <a href="http://nullorundefined.wordpress.com/2011/04/27/advanced-dynamic-template-binding-in-knockout-js/" rel="nofollow">link</a>
while coming up with my solution.

In my html page I have a div that is bound to a list of view models:

&lt;div class="app" 
     data-bind="template: {name: templateSelector, foreach: viewModelBackStack}"&gt;

And my templateSelector method looks like this:

this.templateSelector = function(viewModel)
    if (!_itemTemplate)
      _itemTemplate = ko.computed(function() {return this.template();}, viewModel);

    return _itemTemplate();

var _itemTemplate;

As can be seen, I am constructing a computed observable which returns viewModel's template.

My viewModel looks like this:

function MyViewModel
    this.template = ko.observable("MyTemplate");

I am changing the value of template as a result of an ajax call being completed and I see that computed observable is called correctly as well (I placed an alert in there to verify it), however the bindings in html does not update the template of my viewmodel. Any help will be appreciated.

UPDATE: I found the bug that was causing it not to work. Basically I was including jquery.tmpl plugin before including knockout.js. Removing jquery.tmpl did the trick !