D3 mousedown event deleting the wrong node

前端 未结 2 972
庸人自扰
庸人自扰 2021-01-25 10:28

I am trying to add a delete node feature in this jsfiddle

The refresh method is adding on(\"mousedown\", mousedownNode) event to each circle, b

2条回答
  •  情深已故
    2021-01-25 11:05

    As you said, the correct nodes are getting deleted and the data bound to the also seems correct BUT you're not UPDATING the node texts.

    This is what you have:

    nodeEnter
     .append("text")
     .attr("dx", 12)
     .attr("dy", ".35em")
     .text(function(d) {
      return d.id;
     });
    

    This is what I've changed it to:

    nodeEnter
     .append("text")
     .attr("dx", 12)
     .attr("dy", ".35em");
    
    node.select('text')
     .text(function(d) {
      return d.id;
     });
    

    You can also change this by assigning the nodeText to a variable like this var nodeText = ...

    But here's the point, when you call the refresh after say deleting a node, the exit() selection works BUT the existing nodes DO NOT update by themselves. Hope this makes sense. Read How Selections Work

    JSFIDDLE and here's the snippet:

    EDIT: Removing a draggable SVG element results in an error. To fix, change the exit selection line to:

    node.exit().on('mousedown.drag', null).remove();
    

    that removes the drag event bound before removing the element.

    rect {
      fill: none;
      pointer-events: all;
    }
    
    .node {
      fill: #000;
    }
    
    .cursor {
      fill: green;
      stroke: brown;
      pointer-events: none;
    }
    
    .link {
      stroke: #999;
    }
    
    .node text {
      pointer-events: none;
      font: 10px sans-serif;
    }
    
    path.link {
      fill: none;
      stroke: #666;
      stroke-width: 1.5px;
    }
    
            
        

提交回复
热议问题