4

I'm developing some chart using d3.js. I'm just writing some function to draw some lines on screen. But I found myself writing duplicate code for setting attributes to enter selection and update selection. And even more worse, it's inevitable.

check the below code. Initially, I think it's cool. Every time the input data is changed, I can just call this function, and the chart will just update accordingly: if there's more data coming, new lines will be added, if only data is changed, the existing lines will be redrew.

function drawLines(data){

    svg.selectAll('line')
        .data(data)
        .enter()
        .append('line')
        .attr({
            x1: function(d){
                return d.x1;
            },
            y1: function(d){
                return d.y1;
            },
            x2: function(d){
                return d.x2;
            },
            y2: function(d){
                return d.y2
            }
        })
        .style({
            stroke: 'black',
            'stroke-width': 4
        });;
}

But I find it's not working. The append method doesn't return the update + enter selection together. I'm still working on the enter selection. So I have to write code like below:

function drawLines(data){

    var updateSelection = svg.selectAll('line')
                            .data(data);

    var enterSelection = updateSelection
                            .enter()
                            .append('line');

    enterSelection
        .attr({
            x1: function(d){
                return d.x1;
            },
            y1: function(d){
                return d.y1;
            },
            x2: function(d){
                return d.x2;
            },
            y2: function(d){
                return d.y2
            }
        })
        .style({
            stroke: 'black',
            'stroke-width': 4
        });

    updateSelection
        .attr({
            x1: function(d){
                return d.x1;
            },
            y1: function(d){
                return d.y1;
            },
            x2: function(d){
                return d.x2;
            },
            y2: function(d){
                return d.y2
            }
        })
        .style({
            stroke: 'black',
            'stroke-width': 4
        });
}

As you can see I'm wring duplicate attr, style code just to do same operation on enter selection and update selection. But the enter method section of d3.js documentation says:

The enter selection merges into the update selection when you append or insert. This approach reduces code duplication between enter and update. Rather than applying operators to both the enter and update selection separately, you can now apply them to the update selection after entering the nodes. In the rare case that you want to run operators only on the updating nodes, you can run them on the update selection before entering new nodes.

Now I'm confused about what it means "enter selection merges into the update selection" and "reduces code duplication between enter and update". Am I doing something wrong? As my understanding, the duplicate code between enter and update is inevitable!

2 Answers 2

11

What the documentation means is that once you append elements, they will be part of the update selection. That is, any attributes you set on the update selection will also be set on the elements you have appended from the enter selection just before. So you only need the following code:

var updateSelection = svg.selectAll('line')
                        .data(data);

updateSelection.enter().append('line');

updateSelection
    .attr({
        x1: function(d){
            return d.x1;
        },
        y1: function(d){
            return d.y1;
        },
        x2: function(d){
            return d.x2;
        },
        y2: function(d){
            return d.y2
        }
    })
    .style({
        stroke: 'black',
        'stroke-width': 4
    });

Note that the order of the code is important here -- you need to append the elements of the enter selection before setting the attributes of the update selection.

3
  • You just revolutionized my understing of d3.js. I can finally get rid of all that ducplication I felt made no sense to me. A huge thanks !
    – ereOn
    Aug 3, 2016 at 14:10
  • For d3.v4, have a look on the Interactive General Update Pattern and the merge function. May 21, 2017 at 10:47
  • 1
    I had to do the following to get this to work (d3 3 even): ``` var enterSelection = updateSelection.enter().append('line'); updateSelection.merge(enterSelection).attr(...) ``` Sep 13, 2019 at 18:14
0

You can drop the .style for the update, but you need to keep the x1, y1, x2, x2

The reason for this is d3 is based on a simple principle:

  • update [ records that exist in the data set ]
  • enter [ records that enter the data set ]
  • exit [ records that leave the data set ]

In the update, values with the same 'key' as before can get transformed. So let's say you had a dataset like this:

[ { name: 'A', value: 2 } ]

and it was changed to:

[ { name: 'A', value: 3 } ]

You need to somehow update the existing name 'A' from 2 to 3.

That's why you need the x1, x2, y1, y2, in order to update.

Hope this helps.

2
  • Hi link, my confusion is why one chunk of identical code needs to be written twice on update selection and enter selection. No matter it's the attr or style part of code. As you can see from the d3 documentation. It's saying able to avoid code duplication between enter and update selection. I just don't know how.
    – Aaron Shen
    Jul 1, 2014 at 7:09
  • It technically is code duplication but most times when doing enter, I will set the x1 to 0 put a transition on it and a delay of 1 second and then set the x1 to it's actual value. This way you can see data flying into the data set when it enters. You wouldn't want this on an update so you would just set the x1 to the new value and the data would just grow from old to new. And finally you can make data fly out of the data set on exit. Transitions are a large part of d3 and can be very powerful if used properly. When using transitions it would not be code duplication.
    – link
    Jul 1, 2014 at 7:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.