Knockout.js – lazy loading of templates

knockout.js

So I come from a templating workflow that involves creating a data object (akin to a view model in knockout) passing that to a templating engine (jstemplate in our case), rendering the template using that data object, and appending it to the dom.

How do I achieve a similar work flow with knockout? Is the "if" control flow what I'm looking for? Or sticking my templates in script tags without data-bind attributes and adding them dynamically later and processing the template like ko.applyBindings(viewModel, node)?

I'm curious how others lazy load templates using knockout.

Also, extra credit if you can tell me why the js fiddle below doesn't work as I would expect it to. I'm trying to learn the if control flow binding and this doesn't work.

http://jsfiddle.net/JJgJ7/1/

Best Answer

There are several directions that you can go for something like this:

you can apply different view models to different elements, as you mentioned like:

var viewModelOne = { ...  };
var viewModelTwo = { ...  };
ko.applyBindings(viewModelOne, containerElementOne);
ko.applyBindings(viewModelOne, containerElementOne);

You can even dynamically apply a binding with its data to an element like:

var viewModelOne = { ... };
ko.applyBindingsToNode(containerElement, { template: { name: 'itemTemplate', foreach: items }, viewModelOne);

Would be like this sample: http://jsfiddle.net/rniemeyer/gYk6f/

You can also do something like:

var mainViewModel = {
   sideBarModel = ko.observable(),
   contentModel = ko.observable()
};

Then, bind it like:

<div data-bind="with: contentModel"></div>
<div data-bind="with: sideBarModel"></div>

They, can even be nested like:

<div data-bind="with: contentModel">
   ...
   <div data-bind="with: $root.sideBarModel"></div>
</div>

Since, the models are observable, they can initially be empty and get populated on demand.

You can certainly use named templates in those cases as well like:

<div data-bind="template: { name: "contentTmpl", data: contentModel }"></div>
<div data-bind="template: { name: "sideBarTmpl", data: sideBarModel }"></div>

For the Extra Credit question:

p tags cannot contain other block level elements (like your div). The browser moves it out of the p tag. Replace your div with a span and it will behave like you are expecting (or replace p with div).

Related Topic