Knockout inner binding with HTML
This demonstrates a custom bindHTML handler for knockout that allows used of embedded data binding.
by James Burton
HTML
<textarea data-bind="value: content" style-"width: 100%; height: 10em" rows="10" cols="80"></textarea>
<h6>
Output
</h6>
<div data-bind="bindHTML: content"></div>
JavaScript
/**** Start of ko.bindingHandlers.bindHTML.js *****/
ko.bindingHandlers.bindHTML = {
init: function () {
// we will handle the bindings of any descendants
return { controlsDescendantBindings: true };
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
// must read the value so it will update on changes to the value
var value = ko.utils.unwrapObservable(valueAccessor());
// create the child html using the value
ko.applyBindingsToNode(element, { html: value });
// apply bindings on the created html
ko.applyBindingsToDescendants(bindingContext, element);
}
};
// Enable support for use in virtual elements
ko.virtualElements.allowedBindings.bindHTML = true;
/**** End of ko.bindingHandlers.bindHTML.js *****/
var initialContent = 'boundValue: <span data-bind="text: boundValue"></span>';
ko.applyBindings({
boundValue: ko.observable('data-bind\'ing'),
content: ko.observable(initialContent)
});