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.
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:
You can even dynamically apply a binding with its data to an element like:
Would be like this sample: http://jsfiddle.net/rniemeyer/gYk6f/
You can also do something like:
Then, bind it like:
They, can even be nested like:
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:
For the Extra Credit question:
p
tags cannot contain other block level elements (like yourdiv
). The browser moves it out of thep
tag. Replace yourdiv
with aspan
and it will behave like you are expecting (or replacep
withdiv
).