d3 v4:合并输入和更新选择以删除重复代码

d3 v4: merge enter and update selections to remove duplicate code

我知道 merge 可用于在 d3 v4 中组合输入和更新选择,如此处的简单示例所示:https://bl.ocks.org/mbostock/3808218

我有一个散点图,其中多个变量显示在共享的 x 轴上,用于通过下拉框选择的不同组。选择新组时,将更新整个数据点集,并像这样添加每个变量的点:

.each(function(d, i) {
        var min = d3.min(d.values, function(d) { return d.value; } );
        var max = d3.max(d.values, function(d) { return d.value; } );

    // Join new data with old elements
        var points = d3.select(this).selectAll("circle")
          .data(d.values, function(d) { return (d.Plot); } );

    // Add new elements
        points.enter().append("circle")
          .attr("cy", y(d.key))
          .attr("r", 10)
          .style("opacity", 0.5)
          .style("fill", function(d) { return elevColor(d.Elevation); })
          .merge(points) //(?)
          .transition()
          .attr("cx", function(d) { return x((d.value-min)/(max-min)); });

    // Remove old elements not present in new data
        points.exit().remove();

这整段代码在整体输入选择和整体更新选择(与单个变量相反)中大部分都是重复的,这似乎不太理想。 merge 将如何用于删除此重复代码?

完整示例在这里:http://plnkr.co/edit/VE0CtevC3XSCpeLtJmxq?p=preview

我是同一问题中 solution for your past question, which you linked in this one. I provided that solution in a comment, not as a proper answer, because I was in a hurry and I wrote a lazy solution, full of duplication — as you say here. As I commented 的作者,减少重复的解决方案是使用 merge

现在,在您的代码中,关于 "update" 和 "enter" 选择的设置存在重复:

var update = g.selectAll(".datapoints")
    .data(filtered[0].values);

var enter = update.enter().append("g")
    .attr("class", "datapoints");

update.each(function(d, i){
    //code here
});

enter.each(function(d, i){
    //same code here
});

为避免重复,我们merge 选择。您可以这样做:

var enter = update.enter().append("g")
    .attr("class", "datapoints")
    .merge(update)
    .each(function(d, i) {
        //etc...

这是更新后的 Plunker:http://plnkr.co/edit/MADPLmfiqpLSj9aGK8SC?p=preview