Brad Evans
Brad Evans

Reputation: 728

Can't delete circle in D3 on update

I'm having a lot of trouble getting a circle to delete. In this example I want to delete the circle labeled "2" but it just deletes the last circle in the array. If you uncomment the commented part and comment the graphNodes.splice(2, 1), it works as it should adding a new circle. But the delete won't work.

What am I missing here?

var width = 640,
      height = 480;

  var graphNodes = [
    { id: 0, x: 39, y: 343, r: 15 },
    { id: 1, x: 425, y: 38, r: 15 },
    { id: 2, x: 183, y: 417, r: 15 },
    { id: 3, x: 564, y: 31, r: 15 },
    { id: 4, x: 553, y: 351, r: 15 },
    { id: 5, x: 454, y: 298, r: 15 },
    { id: 6, x: 493, y: 123, r: 15 },
    { id: 7, x: 471, y: 427, r: 15 },
    { id: 8, x: 142, y: 154, r: 15 }
  ];

  var svg = d3.select('body').append('svg')
      .attr('width', width)
      .attr('height', height);

  svg.append('rect')
      .attr('class', 'graph')
      .attr('width', width)
      .attr('height', height)
      .attr('fill', 'lightblue')
      .attr('opacity', 0.3)
      .on('click', function(){
        /*graphNodes.push({
          x: d3.mouse(this)[0],
          y: d3.mouse(this)[1],
          id: graphNodes.length,
          r: 15
        });*/

        graphNodes.splice(2, 1);

        update();
      });

  var nodeGroup = svg.selectAll('.nodes')
      .data(graphNodes, function(d){ return d.id; })
      .enter().append('g')
      .attr('class', 'node');

  nodeGroup.append('circle')
      .attr('cx', function(d) { return d.x })
      .attr('cy', function(d) { return d.y })
      .attr("r", function(d){ return d.r; })
      .attr("fill", "gray");

  nodeGroup.append('text')
      .attr("dx", function(d){ return d.x + 20; })
      .attr("dy", function(d){ return d.y + 5; })
      .text(function(d) { return d.id });

  function update() {

    if(nodeGroup){

      // Update nodes
      var node = nodeGroup.data(graphNodes),
          nodeEnter = node.enter().append('g')
              .attr('class', 'node');

      nodeEnter.append('circle')
              .attr('cx', function(d) { return d.x; })
              .attr('cy', function(d) { return d.y; })
              .attr('r', function(d){ return d.r; })
              .attr('fill', 'gray');

      nodeEnter.append('text')
          .attr("dx", function(d){ return d.x + 20; })
          .attr("dy", function(d){ return d.y + 5; })
          .text(function(d) { return d.id });

      nodeGroup = nodeEnter.merge(node);
      node.exit().remove();
    }
  }

Fiddle

Upvotes: 0

Views: 193

Answers (1)

Mark
Mark

Reputation: 108557

When you re-bind your data in update function, you forgot your key function:

var node = nodeGroup.data(graphNodes, function(d){ return d.id; }),

Update fiddle.

Upvotes: 1

Related Questions