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

橙三吉。 提交于 2019-12-01 12:14:05

I'm the author of the 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 in the same question, the solution for reducing the duplication is using merge.

Right now, in your code, there is duplication regarding the setup of the "update" and "enter" selections:

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
});

To avoid the duplication, we merge the selections. This is how you can do it:

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

Here is the updated Plunker: http://plnkr.co/edit/MADPLmfiqpLSj9aGK8SC?p=preview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!