enter() 和 exit() 如何检测 D3 中的更新数据

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

本文关键字:D3 数据 检测 更新 何检测 exit enter      更新时间:2023-09-26

我正在构建一个小的UI,用户必须在显示的两个SVG中的每一个上选择一个点。

然后,这些点坐标将显示在 SVG 下。我想使用 D3 的数据绑定和 enter()exit() 方法来实现这一点。但是,D3 似乎并不总是更新我显示点坐标的部分,即使我对绑定元素调用 enter() 方法也是如此。但是,删除数据时,exit()方法有效。

这是主要代码:

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();
}

我创建了一个JSBin小提琴来演示这个问题。

第一个问题是你的HTML中有一个空的类point div。这将由.selectAll('.point')选择,并导致数据中的第一个元素不显示。

第二个问题是你没有处理更新选择 - 在某些情况下,你不是在添加新数据,而是修改现有数据。下面的代码更新更新所选内容中的数据的文本。

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(' - ');
});

在此处完成演示。请注意,我通过仅在更新选择上设置文本来稍微简化了代码 - 从输入选择中添加的元素将合并到更新选择中,因此无需执行两次。