异步将节点添加到d3.hierarchy

McG*_*gen 5 javascript d3.js d3.js-v4

我正在用D3(v4)写一棵树,以显示一种特殊类型的数据,其中结构具有很多级别。因此,我决定异步加载每个新级别的数据:当用户单击节点时,我会异步加载其子级。

我达到了预期的结果,但是我不确定这是最好的方法,因为我感觉自己在重写方向盘。有人可以确认我的代码或告诉我一种更好的方式来满足我的需求吗?我在互联网上找不到关于d3和这种异步性的任何信息...

这是简化的代码:

树初始化

// Starting data
var data = {
    "name": "node1",
    "children": [{
        "name": "child1",
        "children": []
    }, { 
        "name": "child2",
        "children": []
    }]
};
// Tree creation
var root = d3.hierarchy(data);
Run Code Online (Sandbox Code Playgroud)

点击代码

function click(d) {
    loadChildrenFromServer(d, fooCallback);
}

function loadChildrenFromServer(d, callback) {
    //Simulating server call
    setTimeout(function () {
        //Mock async data
        var mockchildren = [{
            "name": "asyncChild1",
            "children": []
        }, {
            "name": "asyncChild2",
            "children": []
        }];

        d.data.children = children;    //Updating data
        d.children = [];               //Initializing d3 node children

        children.forEach(function(dchild, index) {
            //Building 'Node' objects and adding them to children
            nodeData.children[index] = makeD3Node(dchild, d, index);
        });

        //Updating all height attributes
        updateHeightAttributeRecursively(d);

        callback();
    }, 100)
}

function makeD3Node(data, parent, index) {
    //I have to use d3.hierarchy because d3 Node constructor is not public
    var node = d3.hierarchy(data);
    node.parent = parent;
    node.depth = parent.depth + 1;
    node.children = null;
    node.data = data;
    node.height = 0;
    node.id = parent.id + '' + index;
    //updating my other attributes...
    return node;
}
Run Code Online (Sandbox Code Playgroud)

我期望某种自动化可以简化此代码(主要是添加节点而不必担心树的每个属性的更新)。

附言:我试图重新创建整个树,将新数据添加到初始数据中并重新调用,d3.hierarchy(root)但是这破坏了我的动画效果。

提前致谢!