Several of the reusable charts examples, such as the histogram, include the following:
// select the svg element, if it exists
var svg = d3.select(this).selectAll("svg").data([data]);
// append the svg element, if it doesn't exist
svg.enter().append("svg") ...
...where this
is the current DOM element and data
is the data that's been bound to it. As I understand it, this idiom allows a chart to be created the first time the chart function is called, but not 'recreated', if you like, following subsequent calls. However, could anyone explain this idiom in detail? For example:
.selectAll("svg")
used and not .select("svg")
?.empty()
used to check for an empty selection?.data()
? (I assume the purpose of this array is simply to return the enter selection.)Thanks in advance for any help.
When this is called the first time, there's no SVG and therefore the .enter()
selection will contain the data passed to it. On subsequent calls, the .enter()
selection will be empty and therefore nothing new added.
Concerning the specific questions:
.selectAll()
returns an array which can then be matched to the array passed to .data()
..empty()
could be used, but it's not necessary -- if the selection is empty, nothing happens. Checking .empty()
would add an if
statement and have exactly the same effect.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With