有没有更好的成语来附加一个<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 block 的结构,而不是使用具有无意义数据的数据连接。
它不仅代码更短,而且意味着当它没有任何意义时,您不会在元素上携带额外的数据属性。其他人也更容易弄清楚您在做什么!
我唯一要更改的是实际保存您用于 .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();
关于javascript - 用于在 enter() 上附加分组元素的 d3 习惯用法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23589738/