2

I am simply trying add and remove elements (nodes/circles) using d3 on a SVG element. However, my code keeps generating the following exception.

Uncaught TypeError: Cannot read property 'ownerSVGElement' of null
    at d3_mousePoint (VM2163 d3.js:1127)
    at d3.mouse (VM2163 d3.js:1122)
    at moved (VM2163 d3.js:1177)
    at VM2163 d3.js:1084
d3_mousePoint @ VM2163 d3.js:1127
d3.mouse @ VM2163 d3.js:1122
moved @ VM2163 d3.js:1177
(anonymous) @ VM2163 d3.js:1084

The problem seems to be with adding dragging behavior to the elements because if I remove .call(someDragFunction) then adding and removing elements doesn't generate that exception (but then, of course, I can't drag those elements around the SVG canvas).

An example is shown here http://plnkr.co/edit/DnSBXSjXhQ2AJsGYvWxE?. If you click "+node" and click on the SVG box, a node will be drawn. If you click "-node" and click on a node/circle drawn, that node will be removed. Only when the last node is attempted to be removed does the exception show.

Any ideas on what I'm doing wrong? Btw, I'm using D3 v3.5.3.

Jane Wayne
  • 8,205
  • 17
  • 75
  • 120

1 Answers1

3

Answer Found

My console error is as follows:

d3.v3.min.js:1 Uncaught TypeError: Cannot read property 'ownerSVGElement' of null
    at J (d3.v3.min.js:1)
    at ao.mouse (d3.v3.min.js:3)
    at a (d3.v3.min.js:3)
    at d3.v3.min.js:1

My svg element

<svg id="charts" width="1356" height="579"></svg>

I have added g element inside svg with drag behavior as follows:

var container = d3.select("#charts")
        .append("g")
        .data([ {"x":node_pos_x, "y":node_pos_y} ])
        .attr("width", node_width)
        .attr("height", node_height)
        .attr("class", classname)
        .attr("id", "node_1")
        .attr("transform", "translate(" + node_pos_x + "," + node_pos_y + ")")
        .call(in_editor_drag);

If I run the following line to remove g#node_1 I got the above console error like you.

d3.select('g#node_1').remove();

the solution is

d3.select('g#node_1').on('mousedown.drag', null);

Now I can remove the g element without any console error.

I found it from here

How to remove d3.behavior.drag().on("drag",...) event handler

Jahangir Alam
  • 801
  • 8
  • 21
  • It took forever, but I tested and it works. After I remove the backing data, I then do `d3.select('circle#nodeId').on('mousedown.drag', null);` before redrawing and the error goes away. Thanks a lot! – Jane Wayne Jan 02 '18 at 04:31