6

just playing around with vis.js for a day now and been through all the docs and examples. I'm trying to figure out the best way to refresh my node and edge data with click events. E.g. say I have one node with no edges, then I click it to add 3 child nodes. Could a vis.js expert suggest best way to do this?

Expected Before:

nodes = [{id: 1,   label:"Parent Node"} ];
edges = [ ];

Expected After click on id 1:

nodes = [{id: 1,   label:"Parent Node"},
{id: 2,   label:"Child Node1"},
{id: 3,   label:"Child Node2"},
{id: 4,   label:"Child Node3"} ];
edges = [ {from: 1, to: 2},
          {from: 1, to: 3},
          {from: 1, to: 4} ];

Then I'd want to collapse and go back to just the parent node w/ no children. I get how to do the event handling, it's the updating and redrawing of the nodes and edges I'm not sure about.

laaposto
  • 11,835
  • 15
  • 54
  • 71
tkelly
  • 635
  • 6
  • 13

1 Answers1

4

Once I posted I figured out my mistake, not using the dynamic DataSet(). So it should be like this:

var nodes = new vis.DataSet([{id: 1,   label:"Parent Node"}]);
var edges = new vis.DataSet([]);

Then you can update like so:

nodes.update({id: 2,   label:"Child Node1"});
nodes.update({id: 3,   label:"Child Node2"});
nodes.update({id: 4,   label:"Child Node3"});

edges.update({from: 1, to: 2});
edges.update({from: 1, to: 3});
edges.update({from: 1, to: 4}); 
Anders Lindén
  • 6,839
  • 11
  • 56
  • 109
tkelly
  • 635
  • 6
  • 13
  • How are you collapsing the node ? Removing from network / hiding or something else ? – rhitz Feb 23 '17 at 06:18
  • @RohitTotala This is pretty old, I don't recall. I wound up switching to D3 instead, it wound up being much easier to work with. – tkelly Mar 01 '17 at 20:46
  • Okay, I did it by making a recursive call updating(hiding) child nodes & edges in network. I'll make a fiddle for SO over this weekend. Thanks. D3 has good options for Hierarchical networks/trees I guess. – rhitz Mar 02 '17 at 10:20
  • @rhitz how's it going with the fiddle from 2017? – barha Jul 26 '22 at 20:01