d3js v4: Add nodes to force-directed graph
<p>I would like to render a <strong>force-directed graph in d3js v4</strong> and provide a function for <strong>dynamically adding new nodes and links</strong> to the simulation. My first attempt (see below) still has some major issues:</p>

<ul>
<li>Already existing nodes and links seem to be ignored by the force
simulation after adding a link</li>
<li>The bindings between simulation nodes and links and their SVG counterparts somehow doesn't work</li>
</ul>

<p>I think I know all the examples (e.g.,<a href="http://bl.ocks.org/ericcoopey/6c602d7cb14b25c179a4" rel="noreferrer"> [1</a>,<a href="http://bl.ocks.org/mbostock/1062288" rel="noreferrer">2]</a>) demonstrating similar functionality for v3, but I would like to do it with v4.</p>

<p>Thanks for your help!</p>

<p><strong>index.html</strong></p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
    &lt;head&gt;
        &lt;meta charset="utf-8"&gt;
        &lt;title&gt;D3 Test&lt;/title&gt;
        &lt;script type="text/javascript" src="js/d3.js"&gt;&lt;/script&gt;
        &lt;script type="text/javascript" src="js/graph.js"&gt;&lt;/script&gt;
        &lt;style type="text/css"&gt;
            .links line {
                stroke: #aaa;
            }

            .nodes circle {
              pointer-events: all;
              stroke: none;
              stroke-width: 40px;
            }
        &lt;/style&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div class="chart-container" style="max-width: 1000px;"&gt;&lt;/div&gt;

        &lt;button class="expand"&gt;Expand graph&lt;/button&gt;

        &lt;script type="text/javascript"&gt;
            //sample graph dataset
            var graph = {
                "nodes": [
                    {"id": "A"},
                    {"id": "B"},
                    {"id": "C"},
                    {"id": "D"},
                    {"id": "E"},
                    {"id": "F"}
                ],
                "links": [
                    {"source": "B", "target": "A"},
                    {"source": "C", "target": "A"},
                    {"source": "D", "target": "A"},
                    {"source": "D", "target": "C"},
                    {"source": "E", "target": "A"},
                    {"source": "F", "target": "A"}
                ]
            }
            //graph container
            var targetElement = document.querySelector('.chart-container');

            var graph = new Graph(targetElement, graph);

            d3.selectAll('button.expand').on('click', function (){
                var nodes = [
                    {"id": "G", "group": 1}
                ];

                var links = [
                    {"source": "F", "target": "G", "value": 1}
                ];

                graph.expandGraph(links, nodes);
            });

        &lt;/script&gt;
    &lt;/body&gt;
&lt;/html&gt;     
</code></pre>

<p><strong>graph.js</strong></p>

<pre><code>var Graph = function(targetElement, graph) {

    var self = this,

        width = targetElement.offsetWidth,

        height = width / 2,

        svg = d3.select(targetElement).append('svg')
            .attr("width", width)
            .attr("height", height),

        simulation = d3.forceSimulation()
                       .force("link", d3.forceLink().id(function(d) { return d.id; }))
                       .force("charge", d3.forceManyBody())
                       .force("center", d3.forceCenter(width / 2, height / 2)),

        link = svg.append("g")
                  .attr("class", "links")
                  .selectAll("line"),

        node = svg.append("g")
                  .attr("class", "nodes")
                  .selectAll("circle"),

        update = function() {

            // Redefine and restart simulation
            simulation.nodes(graph.nodes)
                      .on("tick", ticked);

            simulation.force("link")
                      .links(graph.links);

            // Update links
            link = link.data(graph.links);

            // Enter links
            link = link.enter().append("line");

            // Exit any old links
            link.exit().remove();

            // Update the nodes
            node = node.data(graph.nodes);

            // Enter any new nodes
            node = node.enter().append("circle")
                       .attr("r", 5)
                       .call(d3.drag()
                            .on("start", dragstarted)
                            .on("drag", dragged)
                            .on("end", dragended));

            // Exit any old nodes
            node.exit().remove();

            function ticked() {
                link
                    .attr("x1", function(d) { return d.source.x; })
                    .attr("y1", function(d) { return d.source.y; })
                    .attr("x2", function(d) { return d.target.x; })
                    .attr("y2", function(d) { return d.target.y; });

                node
                    .attr("cx", function(d) { return d.x; })
                    .attr("cy", function(d) { return d.y; });
            }


        },

        dragstarted = function(d) {
            if (!d3.event.active) simulation.alphaTarget(0.3).restart();
            d.fx = d.x;
            d.fy = d.y;
        },

        dragged = function(d) {
            d.fx = d3.event.x;
            d.fy = d3.event.y;
        },

        dragended = function(d) {
            if (!d3.event.active) simulation.alphaTarget(0);
            d.fx = null;
            d.fy = null;
        },

        expandGraph = function(links, nodes) {

            for (var i=0; i &lt; nodes.length; i++) {
                console.log('adding node', nodes[i]);
                graph.nodes.push(nodes[i]);
            }

            for (var i=0; i &lt; links.length; i++) {
                console.log('adding link', links[i]);
                graph.links.push(links[i]);
            }

            update();

        };

        // Public functions
        this.expandGraph = expandGraph;

    update();

};
</code></pre>