在运行时加载knockout.js模板(knockout.js loading templates

2019-07-31 18:57发布

我使用其内置的模板系统knockout.js。 我定义模板像这样:

<script type="text/html" id="subjectItemView">
   <span class="name" data-bind="text: subjectName" />
</script>

然后我用的模板标识所以有此作为脚本的一部分是必要的。

我有一个公平的几个这些模板在我的单页的应用程序,并于最近搬到使用require.js加载需要时,他们说只需要脚本。 我愿做同样的模板,最好使用require.js使我的模块可以列出模板作为依赖关系。

我该怎么做呢?

Answer 1:

我用的是require.js文本插件: http://requirejs.org/docs/api.html#text 。 一旦你的模板文本,你可以将其添加到页面中一个新的脚本(使用类型是text/html或JavaScript的比其他的东西)。

我一直在实际使用直接处理字符串修改的模板引擎,所以,我并不需要额外的脚本标签附加到该页面。

我的代码看起来是这样的:

    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;
            });
        }
    };

我用的stringTemplateEngine样子: https://github.com/rniemeyer/SamplePresentation/blob/master/js/stringTemplateEngine.js



文章来源: knockout.js loading templates at runtime