2

I'm playing around with the "update" pattern in D3.js. I am just creating a simple bar graph that will update the data when you press the "Change" button.

My problem is that when you press the "Change" button, the first three rendered bars do not get re-rendered. I debugged and saw that the data was properly applied (__data__ was correct) but the re-application failed.

Here is my code and a link to it in CodePen:

var myData = [ 100, 200, 300 ];

d3.select('body').append('button').text("Change").on("click", function() {
  myData = [200, 400, 600, 700, 800, 900, 1000];
  update(myData);
});

var svg = d3.select('body').append('svg')
  .attr("class", "chart")
  .attr("y", 30);

var update = function(data) {
  var bars = svg.selectAll('g')
    .data(data);

  var groups = bars.enter()
    .append("g")
    .attr("transform", function(d,i) {return "translate(0," + i*25 + ")"});

  groups
    .append("rect")
    .attr("height", 25)
    .attr("fill", "pink")
    .attr("stroke", "white");

  groups
    .append("text")
    .attr("x", 10)
    .attr("y", 18)
    .attr("fill", "red");

  bars.selectAll("rect")
    .attr("width", String);

  bars.selectAll("text")
    .text(String);
}; 

update(myData); 
4

1 回答 1

2

如果您将.selectAll()更新选择处理中的 更改为.select()

bars.select("rect")
  .attr("width", String);

bars.select("text")
  .text(String);

通过使用selectAll(),您正在访问绑定到您正在选择的元素(即矩形和文本元素)的数据,这些数据在您附加元素时被绑定。此数据尚未更新,因为您仅更新了包含g元素的数据。相反,使用.select()也会将新数据绑定到子元素。

您使用的一般模式是嵌套选择,开始时可能会有点混乱并导致意外结果。

于 2013-05-09T20:18:47.177 回答