knockout.js loading templates at runtime

故事扮演 提交于 2019-12-04 10:52:37

问题


I am using knockout.js with its inbuilt templating system. I define the templates as so:

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

I then use the id of the template so having this as part of the script is a necessity.

I have a fair few of these templates in my single page application and have recently moved to using require.js to load the scripts that are required only when they are required. I would like to do the same with the templates, preferably using require.js so that my modules could list the templates as dependencies.

How do I do this?


回答1:


I use the require.js text plugin: http://requirejs.org/docs/api.html#text. Once you have the template text, you can then append it to the page in a new script tag (with a type that is text/html or something other than javascript).

I have been actually using a modified template engine that handles strings directly, so that I don't need to append extra script tags to the page.

My code looks something like:

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

The stringTemplateEngine that I use looks like: https://github.com/rniemeyer/SamplePresentation/blob/master/js/stringTemplateEngine.js



来源:https://stackoverflow.com/questions/12522658/knockout-js-loading-templates-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!