在 knockout.js 中动态加载视图/模板

Dynamically load views / templates in knockout.js

我有一个 table,我想以两种不同的方式展示它。不同的列数及其内容和单元格的位置。 我想为用户提供一种只需单击一个按钮即可从一个视图切换到另一个视图的方法。

我一开始只是使用 visible 绑定,但后来我意识到这不是正确的方法,因为内容只是 invisible 但它仍在加载DOM。 我在后台复制内容并生成无效的 HTML(例如,table 中的重复 id 属性),这在 jQuery 端产生了问题。

然后我看了一下 the use of knockout templates to accomplish it as in this example,它解决了我以前的问题并且有效,但是<script> 中使用 HTML标签对我来说听起来不是最干净的解决方案。

我不太确定使用 of components 是否可以为这种情况提供任何解决方案,我找不到。

关于如何处理这个问题有什么建议吗?

例如,script 标签内的模板已被 template tags. You might look at this recent answer I wrote 取代。

更新:不是所有的Knockout组件文档都更新了,但是here

另一种选择是dynamically loading templates via AMD (require.js)

使用 knockout components + AMD 绝对是您要找的。看看 knockout 的作者 Steve Sanderson 的 this。它解释了如何使用 korequirejs 构建 SPA。它应该消除你的疑虑

示例:

...
<div data-bind="component: myDynamicComponent"> </div>
...

然后,如果您的 component loader 配置为获取其模板 & |或 viewModel 异步你可以有 myDynamicComponent 作为一个可观察的:

function RootViewModel(){
    var self = this;
    this.myDynamicComponent = ko.observable('some-component');

    this.someButtonClicked = function() { 
        self.myDynamicComponent('some-other-component'); // this should render your other component async (only if you configured your component loader to do so)
    }
}