knockout.js在运行时加载模板

Ara*_*and 8 template-engine requirejs knockout.js

我正在使用knockout.js及其内置的模板系统.我将模板定义为:

<script type="text/html" id="subjectItemView">
   <span class="name" data-bind="text: subjectName" />
</script>
Run Code Online (Sandbox Code Playgroud)

然后我使用模板的id,因此将此作为脚本的一部分是必要的.

我的单页面应用程序中有很多这些模板,并且最近使用require.js来加载仅在需要时才需要的脚本.我想对模板做同样的事情,最好使用require.js,这样我的模块就可以将模板列为依赖项.

我该怎么做呢?

RP *_*yer 10

我使用require.js文本插件:http://requirejs.org/docs/api.html#text .获得模板文本后,可以将其附加到新脚本标记中的页面(类型为text/htmljavascript以外的类型).

我实际上一直在使用一个直接处理字符串的修改模板引擎,因此我不需要在页面上附加额外的脚本标记.

我的代码看起来像:

    this.activate = function() {
        //load view model from the server
        if (!this.loaded) {
            require(["modules/" + name, "text!../templates/" + self.template + ".html"], function(Module, template) {
                ko.templates[self.template] = template;
                self.data(typeof Module === "function" ? new Module() : Module);
                self.loaded = true;
            });
        }
    };
Run Code Online (Sandbox Code Playgroud)

我使用的stringTemplateEngine如下所示:https://github.com/rniemeyer/SamplePresentation/blob/master/js/stringTemplateEngine.js