Use the knockoutjs virtual element to create the html part on the fly

I am trying to use a "virtual element" with an html binding to create the html part on the fly, but not with the message: "The html binding cannot be used with virtual elements." Here is jsfiddle: http://jsfiddle.net/d3Dpp/ .

Does anyone know if there is a workaround?

+5
source share
3 answers

Well, after some knockout games, I see that it's possible.

Working example here

http://jsfiddle.net/d3Dpp/42/

Unfortunately, this requires duplication of some of the internal functions of the knockout.

UPDATE

KnockoutJS 2.2.1 , , :

ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);

, html - . Martijn.

+7

Artem KnockoutJS 2.2.1 :

http://jsfiddle.net/YZzDe/2/

:

  • , ( )
  • html-, html
  • .

{
    var overridden = ko.bindingHandlers['html'].update;

    ko.bindingHandlers['html'].update = function (element, valueAccessor) {
        if (element.nodeType === 8) {
            var html = ko.utils.unwrapObservable(valueAccessor());

            ko.virtualElements.emptyNode(element);
            if ((html !== null) && (html !== undefined)) {
                if (typeof html !== 'string') {
                    html = html.toString();
                }

                var parsedNodes = ko.utils.parseHtmlFragment(html);
                if (parsedNodes) {
                   var endCommentNode = element.nextSibling;
                   for (var i = 0, j = parsedNodes.length; i < j; i++)
                      endCommentNode.parentNode.insertBefore(parsedNodes[i], endCommentNode);
                }
            }
        } else { // plain node
            overridden(element, valueAccessor);
        }
    };
}
ko.virtualElements.allowedBindings['html'] = true;
+7

:

<div data-bind="html: html"></div>​​​​​​​​​​​​​​​​​​​​​

innerHtml div html.

0

All Articles