Knockout.JS如何绑定dom元素绑定

时间:2013-02-07 22:05:33

标签: knockout.js

我想绘制使用knockout绑定在JS中生成的类别树, 但是我不能用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());

如果在代码上方运行,则打印,

[对象HTMLUListElement]

如何与Element数据进行绑定?

3 个答案:

答案 0 :(得分:4)

html绑定期望html内容为文本。要让绑定接受DOM元素,我认为你需要一个自定义绑定 - 例如(在这里使用jquery进行dom操作):

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

然后像:

一样使用它
<div data-bind="element: categoryTree"></div>

有关自定义绑定的详细信息:http://knockoutjs.com/documentation/custom-bindings.html

答案 1 :(得分:1)

将appendSubCategories替换为:

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>";
}

答案 2 :(得分:1)

或者您可以像这样简单地更新observable:

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