繁体   English   中英

d3用于在enter()上附加分组元素的习语?

[英]d3 idiom for appending grouped elements on enter()?

是否有更好的习惯用法将<svg:g>分组的元素集附加到enter()选择的容器中作为通用更新模式的一部分?

var cell = d3.select(this); // parent container

cell = cell
  .selectAll('.plot').data([0]);   // seems kludgy

cell
  .enter().append('g').classed('plot',true);  // append the wrapping <g> element

cell = cell
  .selectAll("circle")
  .data(_.values(slice));

cell
  .enter().append("circle"); // general enter() -- create plot elements

cell.attr() // etc.  general update--style plot elements

cell
  .exit().remove();

当然,

if ( cell.select('g.plot').empty() ) {
  cell = cell.append('g').classed('plot', true);
}

而不是前两个语句也会这样做,但这似乎是一个非常常见的操作,而selectAll().data([0])似乎做作 - 是否有更优雅的d3成语?

如果需要创建一个元素或者另外选择它,我通常会使用类似于if块的结构,而不是使用无意义数据的数据连接。

它不仅代码更短,而且意味着当元素没有任何意义时,你不会在元素上携带额外的数据属性。 其他人也更容易弄清楚你在做什么!

我唯一要改变的是实际保存你用于.empty()测试的选择,因为如果它不是空的你就会使用它。 (您可以使用另一个变量来保存此选择,但是d3.select(this)并不是一个重复的高计算方法调用,即使这样,当您第一次创建组时,您也只会重复一次。)

var plot = d3.select(this) // this is the parent container
             .selectAll('g.plot'); //select the plot group if it exists

if ( plot.empty() ) 
    plot = d3.select(this).append('g').classed('plot',true);
           //create the plot group if necessary

var cell = plot.selectAll("circle") //now select/create data elements as usual
  .data(_.values(slice));

cell
  .enter().append("circle"); // general enter() -- create plot elements

cell.attr() // etc.  general update--style plot elements

cell
  .exit().remove();

只需为您需要的每组新元素添加“g”。

var cell = d3.select(this)
  .append("g")
    .attr("class","plot")
    .selectAll("circle")
    .data(…);

cell.enter().append("circle")
    .attr(…);

cell.exit().remove();

什么在这里不起作用?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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