递归异步JS - 如何知道遍历每个节点的时间?

时间:2017-04-26 10:22:03

标签: javascript asynchronous recursion

我有一个项目树{ul>li),有潜在的子树,每个节点在点击时加载到ajax中。

我需要一个客户端搜索方法,它将打开每个节点,并搜索输入文本。更重要的是,对于这个问题,该方法应该在搜索开始时在列表上方显示“加载”面板,并在搜索完成时隐藏面板。

我无法找到方法知道所有项目何时被打开。

当前状态基本上是这样的(删除了文本的实际发现,因为它与面板事物无关):

function displayLoading(node) {
    // returns a created loading panel "attached" to the node
}
function hideLoading(loader) {
    // destroys the loading panel
}

// This is called on page load
function bindDisplay() {
    var tree = $("#tree");

    // initialize: load the root elements
    // -> displays then hides the loading panel just fine
    var loader = displayLoading(tree);
    loadChildren(tree, function () {
        hideLoading(loader);
    });

    // this is where I can't imagine how to handle "my nodes have all been opened"
    var search = function search() {
        var openChildren = function openChildren(ul) {
            ul.find('li').each(function () {
                loadChildren($(this), function (ul) {
                    if (ul && ul.length > 0) {
                        openChildren(ul);
                    }
                });
            });
        }
        openChildren(tree);
    };

    $('#searchbutton').on('click', search);
}

function loadChildren(node, callback) {
    // we already know there are no more sub items (see below)
    if (node.data('last') && node.data('last') === true) {
        if (callback) { callback(); }
        return;
    }

    // there already are sub-items that have been loaded once upon a time
    if (node.find('ul').length > 0) {
        if (callback) { callback(node.find('> ul')); }
        return;
    }

    // load children nodes
    var apiUrlGetChildren = $("#tree").data('apigetchildren');
    $.get(apiUrlGetChildren, { id: node.data('id') })
    .done(function (data) {
        // parses data and adds new ul/li to the tree
        // note that I know when there are no sub-items in the loaded items,
        // and in this case I add : newNode.data('last', true)
        var newUl = processData(node);
        node.append(newUl);

        if (callback) { callback(newUl); }
    });
}

0 个答案:

没有答案