Andrew
unread,May 9, 2012, 11:47:42 PM5/9/12Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
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.