Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

knockout.js - lazy loading of templates

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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...