2017-09-06 1 views
0

D3.js 트리 레이아웃 버전 3에서 https://jsfiddle.net/CJ_Shijo/e7osumLp/ 예제로 작업 중입니다. jsfiddle 예제에서 자식 노드를 클릭하는 동안 관련없는 부모 노드를 숨길 수 있습니다. 또한 리프 노드를 클릭하는 동안 노드를 동적으로 추가 할 수 있습니다. 아래 두 함수 은 리프 노드에 노드를 동적으로 추가하는 데 사용하고 있습니다.트리 레이아웃 v4 (버전 4)를 사용하여 D3.js의 리프 노드에 노드를 동적으로 추가합니다.

function updateJson(node) { 
    var associatedItems = getNewData(node); 
    node._children = associatedItems; 
    // if the node has visible children, make them invisible 
    if (node.children) { 
     node._children = node.children; 
     node.all_children = node.children; 
     node.children = null; 
    } 
    // if the node has invisible children, make them visible 
    else { 
     node.children = node._children; 
     node.all_children = node._children; 
     node._children = null; 
    } 
    // update the view to reflect the new changes 
    if (node.children) { 
     node.children.forEach(function (n) { 
      n.hidden = false; 
     }); 
     if (node.parent) { 
     node.parent.children = [node, ]; 
     node.parent.hidden = true; 
     node.parent.children.filter(function (n) { 
      return n !== node; 
      }).forEach(function (n) { 
       n.hidden = true; 
      }); 
     } 
    } 

} 

function getNewData(node) { 
/* Return a list of things that will be added as children to the json. */ 
    return [{ 
      name: "E", 
     }, { 
      name: "F", 
     }, { 
      name: "G", 
     } 
    ]; 
} 

나는 d3 V3 버전을 사용하여이 기능을 달성했다. 나는 d3 V4 버전과 동일한 기능을 달성해야합니다.

이 jsfiddle을 사용하여 d3 v4 버전을 시작했습니다. https://jsfiddle.net/CJ_Shijo/km4txwna/ 예.

다음과 같이 플랫 json 데이터가 있습니다.

var flatData = [ 
    {"name": "Top Level", "parent": null}, 
    {"name": "Level 2: A", "parent": "Top Level" }, 
    {"name": "Level 2: B", "parent": "Top Level" }, 
    {"name": "Son Of A", "parent": "Level 2: A" }, 
    {"name": "Daughter Of A", "parent": "Level 2: A" } 
]; 

아래의 d3 방법을 사용하여 계층 적 (트리) 데이터를 생성했습니다. 내가 제대로 부착되지 않은 잎 nodes.Child 노드에 동적으로 노드를 추가하는 문제에 직면하고있는 V4 버전 예에서

var treeData = d3.stratify() 
       .id(function(d) { return d.name; }) 
       .parentId(function(d) { return d.parent; }) 
       (flatData); 

    treeData.each(function(d) { d.name = d.id; }); 
    var root = d3.hierarchy(treeData, function(d) { return d.children; }); 

. V4 버전에서 어느 누구도 나를 도울 수 있습니까?

답변

1

d3 v4에서 리프 노드에 노드를 추가하는 데 도움이되는 함수가 있습니다.

function addNodes(selectedNode) { 

    var data = [{"name":"First"},{"name":"Second"},{"name":"Third"}]; 

    if (!selectedNode.children) { 
      var childArray = []; 
     } 

    selectedNode.height = selectedNode.height + 1; 

    data.forEach(function (d) { 
     var obj = d3.hierarchy(d); 
     obj.data.parent = selected.name; 
     obj.depth = selected.depth + 1; 
     obj.parent = selected; 
     obj.name = d.name; 
     childArray.push(obj); 
    }); 
selectedNode.children = childArray; 

}

관련 문제