【问题标题】:How are enter() and exit() detecting updated data in D3?enter() 和 exit() 如何检测 D3 中的更新数据?
【发布时间】:2015-01-29 13:15:25
【问题描述】:

我正在构建一个小型 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 小提琴来演示这个问题。

【问题讨论】:

    标签: javascript data-binding d3.js


    【解决方案1】:

    第一个问题是您的 HTML 中有一个空的 divpoint。这将由.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(' - ');
    });
    

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

    【讨论】:

    • 感谢您的快速回答拉斯。我理解第一个问题,但我对第二个问题有点困惑。我看到您的代码按预期工作,但是在比较我们的相互代码时,我注意到您只是将text() 回调在函数中进一步向下移动,我不明白此操作将如何改变节点更新的任何内容。
    • coordinatesElements 是更新选择 -- 您不需要调用像 .enter().exit() 这样的附加函数。因此,通过移动代码,我正在运行在更新选择中设置文本的函数,此时还包含从.enter() 选择中添加的新元素。
    • 感谢您的解释。我刚刚注意到您更新的代码使“X”符号允许删除一对坐标被text() 调用覆盖。 Here is the final working code.
    猜你喜欢
    • 2014-12-12
    • 1970-01-01
    • 2012-01-22
    • 2012-01-14
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    相关资源
    最近更新 更多