简体   繁体   中英

How are enter() and exit() detecting updated data in D3?

I am building a small UI where the user has to select a point on each of the two SVGs shown.

These points coordinates are then shown under the SVGs. I would like to achieve this using D3's data-binding with the enter() and exit() methods. However it seems that D3 doesn't always update the part where I display the points coordinates, even if I call the enter() method on the bound elements. When removing data, the exit() methods works however.

Here is the main code :

function showPoints() {
  var coordinatesElements = d3.select('#coordinates').selectAll('.point').data(points);
  coordinatesElements.enter().append('div').classed('point', true)
    .text(function (d) {
      var textParts = [];
      if (d.firstSvg) { textParts.push('first : '+JSON.stringify(d.firstSvg)); }
      if (d.secondSvg) { textParts.push('second : '+JSON.stringify(d.secondSvg)); }
      return textParts.join(' - ');
    })
    .append("span")
    .classed('removeCalibrationPoint', true)
    .html(" X")
    .on('click', function(d, i) {
      points.splice(i, 1);
      showPoints();
    });

  coordinatesElements.exit().remove();
}

I have created a JSBin fiddle that demonstrates the problem.

The first problem is that you have an empty div of class point in your HTML. This will be selected by the .selectAll('.point') and cause the first element in your data not to show up.

The second problem is that you're not handling the update selection -- in some cases, you're not adding new data, but modifying existing data. The following code updates the text for the data in the update selection.

coordinatesElements.text(function (d) {
  var textParts = [];
  if (d.firstSvg) { textParts.push('first : '+JSON.stringify(d.firstSvg)); }
  if (d.secondSvg) { textParts.push('second : '+JSON.stringify(d.secondSvg)); }
  return textParts.join(' - ');
});

Complete demo here . Notice I've simplified the code slightly by setting the text only on the update selection -- elements added from the enter selection merge into the update selection, so there's no need to do it twice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM