Reputation: 511
What are the pros and cons for these two approaches? What controls which way the bars fly in e.g. from top to bottom or left to right? Why doesn't bar.exit().remove() work with Option 2?
Option 1 https://jsfiddle.net/2523onr3/ Option 2 https://jsfiddle.net/sjp700/2523onr3/3/
bar.exit().remove()
svg.selectAll(".bar").remove();
Upvotes: 1
Views: 513
Reputation: 102198
You have two substantially different approaches here.
The first option:
bar.exit().remove()
Is a proper "exit" selection. This is what it does:
Given your update selection...
var bar = svg.selectAll(".bar")
.data(dataset, function(d) {
return d.label;
});
... your exit selection compares the data with the selected DOM elements. If you have more elements than data, the extra elements (that is, the elements left without data) will populate this selection. Then, when you do remove()
, you remove the elements present in this selection.
Before doing remove()
, you can do any transition you want with your exit selection: moving right, left, up, changing colour, changing opacity etc. So, you control "which way the bars fly", not only in the exit selection but in the enter and update selections as well.
On the other hand, your second option...
svg.selectAll(".bar").remove();
... simply selects everything with a class named bar
(it can be a circle, a text, a rectangle, a pentagon, it doesn't matter...) and remove all elements with that class.
Upvotes: 1