5

I'm new to D3.js. I'm trying to remove a node from tree layout, but I couldn't find the way to do that. This is a sample tree layout.
https://dl.dropbox.com/u/7098/tree/dynamic3.html

I want to remove like this dynamically:
https://dl.dropbox.com/u/7098/tree/aaa.gif

I believe that I should some operation to root json object...
If you guys have idea, please let me know.

TWA
  • 12,756
  • 13
  • 56
  • 92
Toshi
  • 51
  • 1
  • 3

2 Answers2

2

this makes explicit seb's answer. where you set up your click handler, put this:

.on("click", function(d) { 
    if (d.parent && d.parent.children){
        console.log('removing ' + d.name);
        var nodeToDelete = _.where(d.parent.children, {name: d.name});
        if (nodeToDelete){
            d.parent.children = _.without(d.parent.children, nodeToDelete[0]);
        }
    }
});

that should get you what you want. make sure to call whatever method draws the tree from the source data, which is now modified. note: i'm using the underscore library to make use of _.where and _.without, although you could do this with pure js or with another library. some of the checks are for convenience and to prevent deletion of the root node, for example.

p.s. since you'll probably want to keep your expand/collapse behavior, then just put a conditional in the click callback to check for a modifier key to specify node deletion with, such as d3.event.altKey.

Dominick
  • 437
  • 5
  • 16
0

The principles you'll need to follow are answered in Collapse/expand child nodes of tree in d3.js?. That example shows how to collapse a tree on the click handler for a node.

If you modify the data structure that you've passed to the layout manager, then the tree will update accordingly. In the case of collapsing a tree layout in the example above, you remove a node's children attribute: the value of children is stashed in a variable _children so the children can be toggled back again. See the toggle function for details.

To delete a node, then follow the same logic, but remove the node that receives the click event from it's parent's list of children. To find the parent, you can either walk the tree in the click handler, or store a reference to each parent in the data structure.

Community
  • 1
  • 1
seb
  • 3,646
  • 26
  • 21