Knockout.JS How to bind dom element bind

2019-08-30 18:29发布

问题:

I want to draw my category tree that generated in JS using knockout binding, but I can not binding with DOM Element.

<div id="category_list" data-bind="html:categoryTree">
    List Area   
</div>

//JS

function appendSubCategories(categories) {
    var container = document.createElement("ul");
    $.each(categories, function (i, category) {
        var currentNode = document.createElement("li");
        var span = document.createElement("span");
        span.setAttribute("style", "margin-left: 2px");
        span.className = "folder";
        span.appendChild(document.createTextNode(category.Name));
        currentNode.appendChild(span);

        if (category.Subfolders.length > 0) {
            currentNode.appendChild(appendSubCategories(category.Subfolders));
        }
        container.appendChild(currentNode);
    });
    return container;
}

function CategoryViewModel() {
    var self = this;
    self.categoryTree =ko.observable(); 

    $(function () {
        $.getJSON("/Admin/Category/getCategoryList", function (categoryList) {
            self.categoryTree(appendSubCategories(categoryList));

            //self.categoryTree("<p>This is working</p>);
            //$("#category_list").html(categoryTree);

            $(".folder").click(function () {
                console.log(this);
            });
        });


    });
}// End CategoryViewModel
ko.applyBindings(new CategoryViewModel());

If run above code, it print,

[object HTMLUListElement]

How should I do to make bind with Element data?

回答1:

Or you could simply update the observable like this:

var html = $(appendSubCategories(categoryList)).html();
self.categoryTree(html);


回答2:

The html binding expect the html content as text. To have the binding accept DOM elements i think you need a custom binding - for example (using jquery here for dom manipulation):

ko.bindingHandlers.element = {
    update: function(element, valueAccessor) {
    var elem = ko.utils.unwrapObservable(valueAccessor());
    $(element).empty();
    $(element).append(elem);
}

and then use it like:

<div data-bind="element: categoryTree"></div>

For more info on custom bindings: http://knockoutjs.com/documentation/custom-bindings.html



回答3:

Replace appendSubCategories with this:

function appendSubCategories(categories) {
    var container = "<ul>";
    $.each(categories, function (i, category) {
        container += '<li><span class="folder" style="margin-left: 2px;">' + category.Name + '</span>';
        if (category.Subfolders.length > 0) {
            container += appendSubCategories(category.Subfolders);
        }
        container += '</li>';
    });
    return container + "</ul>";
}


标签: knockout.js