0

我想绘制使用淘汰绑定在 JS 中生成的类别树,但我无法与 DOM 元素绑定。

<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]

我应该怎么做才能与元素数据绑定?

4

3 回答 3

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

于 2013-02-07T22:27:57.087 回答
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>";
}
于 2013-02-07T22:34:15.383 回答
1

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

var html = $(appendSubCategories(categoryList)).html();
self.categoryTree(html);
于 2013-02-07T22:53:32.900 回答