比方说,有一个简单的HTML模板:KnockoutJS:注入模板(组件)applyBindings后
<div>
<content-a></content-a>
<content-b></content-b>
</div>
我注册使用(用于分量“内容为”例子)这两个组件:
ko.components.register('content-a', {
viewModel: { instance: vm }, // ViewModel for that component
template: template // template of that component
});
再后来我注入HTML模板到指定的HTML元素:
var node = document.getElementById('content');
node.innerHTML = template; // here "template" represent just a HTML string (described at the very top)
ko.applyBindings(vm, node); // here vm represents ViewModel instance
但是,我应用绑定时会呈现所有注册的组件。
有没有办法按需渲染组件?不适用于applyBindings应用。
换句话说:我想渲染主要内容,applyBindings,然后再按需求添加和渲染新组件。
是最后循环,使用“看得见”的结合是一个好主意。这使我朝着正确的方向前进。 不过,我正在考虑在需要时向DOM注入模板。在这种情况下,“组件”不会有多大帮助,因为它们在应用绑定后被添加到DOM中。 – 2014-10-08 08:38:28