9

Manipulation methods of vis.js only include addNodeMode(), but not something like addNode(). I wonder if there's some nice way to create a node on click. May be by manipulating the data instead of network itself?

Of'course, one may go

network.on('click',function(params){
    if((params.nodes.length == 0) && (params.edges.length == 0)) {
        network.addNodeMode(); // doesn't add, one more click needed
        //# generate click in the same place. Use params.pointer.canvas
        //  or params.pointer.DOM to set appropriate coordinates
    }
})

but then we have also to prevent infinit loops since we generate a click event in a click handler..

YakovL
  • 7,557
  • 12
  • 62
  • 102

2 Answers2

7

Ok, here's my current implementation:

...
data = ...
nodes = new vis.DataSet(data.nodes); // make nodes manipulatable
data = { nodes:nodes, edges:edges };
...
var network = new vis.Network(container, data, options);

network.on('click',function(params){
    if((params.nodes.length == 0) && (params.edges.length == 0)) {
        var updatedIds = nodes.add([{
            label:'new',
            x:params.pointer.canvas.x,
            y:params.pointer.canvas.y
        }]);
        network.selectNodes([updatedIds[0]]);
        network.editNode();
    }
})

It's not perfect since it actually creates a node and starts editing it, so if we cancel editing, the node stays. It also creates unwanted shadows of nodes. But it's already a working prototype which is enough to start with.

YakovL
  • 7,557
  • 12
  • 62
  • 102
6

You can add nodes dynamically by using the update method of the vis.DataSet class. See this documentation page for details: https://visjs.github.io/vis-data/data/dataset.html

philoj
  • 468
  • 2
  • 13
pgoldweic
  • 467
  • 3
  • 9