0
votes

What is the best way to apply a binding to a text fragment?

I came ip with the following code:

var textFragment = '<div><p data-bind="text: text"></p></div>',
    htmlTemplate = ko.utils.parseHtmlFragment(textFragment);

ko.applyBindings({
    text: "text"
}, htmlTemplate[0]);

alert(htmlTemplate[0].innerHTML);
document.getElementById("test").innerHTML = htmlTemplate[0].innerHTML;

(Fiddler)

which creates a dom node and applys abinding to it and then I insert it to the page. I looked throw the knockout code and saw, that there are several functions for rendering templates and I'm wondering if those methods would work better. I tried to used them but the resulting code was longer and didn't work as expected.

Regards, Stefan

(Not: this is only a simple demo to demonstrate my problem, I'm using it in a custom binding handler).

1
Can you explain how you tried to use the templates? Because it is much more simpler if you are using them correctly: jsfiddle.net/Q3cUa - nemesv
Yeah, I wanted to accomplish something else. I wanted to create a cosutm binding handler which creates a few DOM objects an then leaves them to jQueryUI. That's whay I couldn't use the normal templates because then the kncout binding would itnerfeat with jQUeryUI which might move the DOM objects out of the binding context, causing knocout to crash..... It's a pretty none standrard problem I have her - Stefan
How is that comment helpful @nemesv? He does not want the template in the DOM as a script. - Anders

1 Answers

1
votes

Sounds like you want to override the default source engine.

//string template source engine
var stringTemplateSource = function (template) {
    this.template = template;
};

stringTemplateSource.prototype.text = function () {
    return this.template;
};

var stringTemplateEngine = new ko.nativeTemplateEngine();
stringTemplateEngine.makeTemplateSource = function (template) {
    return new stringTemplateSource(template);
};

You can then use it as default engine like

ko.setTemplateEngine(stringTemplateEngine);

Or use it for specific templates from a custom binding like

var myTemplate = '<div><p data-bind="text: text"></p></div>';
ko.renderTemplate(myTemplate, bindingContext.createChildContext(valueAccessor()), { templateEngine: stringTemplateEngine }, element, "replaceChildren");