Dynamic knockout patterns

I have a viewmodel whose template I want to dynamically change at runtime when my application state changes. I referred to the link coming up with my solution.

On my html page, I have a div tied to a list of view models:

<div class="app" data-bind="template: {name: templateSelector, foreach: viewModelBackStack}"> </div> 

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 you can see, I create a computed observable that returns a viewModel template.

My viewModel looks like this:

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

I change the value of the template as a result of the completion of the ajax call, and I see that the calculated observable is called correctly (I posted a warning there to check it), however the bindings in html do not update the template of my view model. Any help would be appreciated.

UPDATE: I found an error that made it not work. I basically turned on the jquery.tmpl plugin before including knockout.js. Removing jquery.tmpl did the trick!

+4
source share
1 answer

I do not see a problem with your code, unless it is in the part where you are updating the template observed as a result of an AJAX call. Make sure you have a link to your view model and set it as observable vm.template(newValue); and do not recreate the observed.

Here is your code working: http://jsbin.com/ipijet/5/edit#javascript,html,live

It should be noted that the bindings are already performed in the context of the calculated observable, so there is no need to create your own templateSelector in your function.

You can simply create a function that returns your observable directly, like:

 this.getTemplate = function(data) { return data.template(); }; 

http://jsbin.com/ipijet/3/edit#javascript,html,live

Here is an article I wrote some time ago on this topic: http://www.knockmeout.net/2011/03/quick-tip-dynamically-changing.html

+3
source

All Articles