How do I dynamically add a named template to Knockout without having to create a DOM element?

896 views
Skip to first unread message

Andrew

unread,
May 9, 2012, 11:47:42 PM5/9/12
to KnockoutJS
Hi All,

I need to be able to add a new named Knockout template on the fly
without polluting the DOM - is there a way to do this? I've been
hunting through the KO code and haven't found an easy answer so far.

The scenario is a reusable control using KO bindings that may appear
multiple times on the same page, or not at all, and I want this thing
to be as self-contained as possible, i.e., it creates its own
templates if they don't already exist. Any other suggestions for ways
to do this would be most welcome.

I've tried dynamically adding a SCRIPT element to the page and this
actually works really well, except in .... IE9 where the domElement
text property returns an empty string:

ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function
(templateSource, bindingContext, options) {
var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9
cloneNode doesn't work properly
templateNodesFunc = useNodesIfAvailable ?
templateSource['nodes'] : null,
templateNodes = templateNodesFunc ? templateSource['nodes']
() : null;

if (templateNodes) {
return
ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
} else {
var templateText = templateSource['text']();
<-------------- returns "" in IE9 for dynamically-added SCRIPT
elements
return ko.utils.parseHtmlFragment(templateText);
}
};

Cheers, Andrew.

rpn

unread,
May 9, 2012, 11:53:46 PM5/9/12
to knock...@googlegroups.com
One option in your plugin would be to use the templateSource functionality to create a template engine that is able to work with templates that come from strings.  Here is a post that talks about one approach to doing this:  http://www.knockmeout.net/2011/10/ko-13-preview-part-3-template-sources.html.  So you would use this template engine in your plugin (or share it across plugins).  If you need more information/help, then let me know.

Hope this helps.

Andrew

unread,
May 10, 2012, 4:52:36 PM5/10/12
to KnockoutJS
Thanks, rpn, that looks like exactly what I need !

On May 10, 3:53 pm, rpn <rnieme...@gmail.com> wrote:
> One option in your plugin would be to use the templateSource functionality
> to create a template engine that is able to work with templates that come
> from strings.  Here is a post that talks about one approach to doing this:  http://www.knockmeout.net/2011/10/ko-13-preview-part-3-template-sourc....
Reply all
Reply to author
Forward
0 new messages