Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove node on tree layout D3.js?

Tags:

d3.js

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.

like image 699
Toshi Avatar asked Nov 04 '22 10:11

Toshi


1 Answers

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.

like image 124
Dominick Avatar answered Nov 17 '22 05:11

Dominick