score:11

Accepted answer

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.

score: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.


Related Query

More Query from same tag