borisyankov/DefinitelyTyped — pull request #259 by danludwig (2013-02-07 18:04:48+00:00)
Title: Add ko.utils.setHtml to KnockoutUtils interface (2 overloads total).

I needed this to author a custom knockout bindingHandler in TypeScript. The bindingHandler invokes ko.utils.setHtml(element, valueAccessor()), similar to how knockout's internal html bindingHandler invokes the same utility function.

Relevant knockout source code:

ko.utils.setHtml = function(node, html) {
ko.utils.emptyDomNode(node);

// There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
html = ko.utils.unwrapObservable(html);

if ((html !== null) && (html !== undefined)) {
if (typeof html != 'string')
html = html.toString();

// jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
// for example
elements which are not normally allowed to exist on their own.
// If you've referenced jQuery we'll use that rather than duplicating its code.
if (typeof jQuery != 'undefined') {
jQuery(node)['html'](html);
} else {
// ... otherwise, use KO's own parsing logic.
var parsedNodes = ko.utils.parseHtmlFragment(html);
for (var i = 0; i < parsedNodes.length; i++)
node.appendChild(parsedNodes[i]);
}
}
};