chungtinhlakho
chungtinhlakho

Reputation: 930

D3js path update enter and exit

What am I missing?
I am allowing users to remove and plot their own data point. My line path is drawn with this and it works fine.

 let self = this;
        let line = D3['line']()
            .x(function (d) { return self.getColX(d.x); })
            .y(function (d) { return self.getRowY(d.y); });
        this.group = this.canvas.append("g")
            .attr("transform", "translate(25,25)");

        //bind the data
        this.group.selectAll("path")
            .data(this.data[this.site].drawLine)
            .enter()
            .append("path")
            .attr("d", line)
            .attr("fill", "none")
            .attr("stroke", "black");

        this.group.selectAll('path').exit().remove()

My problem is, if I pop the last coordinates out and add a new one, call the draw function, the new points gets added correctly but the old points doesn't get remove.

For example: my line goes from (x,y): (1,3) to (3,6) to (7,8), if i remove (7,8) and replace that with 5,6. i will see a new line from (3,6) to (5,6) but the line from (3,6) to (7,8) which is no longer in the data array still there.

Upvotes: 1

Views: 2084

Answers (1)

cvsguimaraes
cvsguimaraes

Reputation: 13240

The enter() and exit() selections are created after D3 compares your selection with the data provided. So they are available in the return of these calls:

this.group.selectAll("path")
            .data(this.data[this.site].drawLine)

And that's why new data is appended, enter() works just fine.

With this.group.selectAll('path').exit().remove() you create a new selection but is not comparing the selection against any data, therefore enter() and exit() selections aren't available to work with.

Long story short, just apply .exit().remove() to your initial selection and it should work. Something like this:

    let update = this.group.selectAll("path")
        .data(this.data[this.site].drawLine)

    update.enter()
        .append("path")
        .attr("d", line)
        .attr("fill", "none")
        .attr("stroke", "black")

    update.exit()
        .remove()

Upvotes: 3

Related Questions