enter() and exit()

This is where the magic happens around binding data. In D3.js, once you have selected elements, with the enter() method you are creating nodes (referenced as d in function(d)) for incoming data and with exit() you remove those nodes if they are no longer needed. Taking the following example, all paragraphs are selected and an array of data is entered into the selection. Once the data has been entered, a node is created for each single array element which allows it to loop through each node and apply some logic to it as shown in the following code:

<html>
<body>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js"></script>
<script>
d3.select("body")
.selectAll("p")
.data([4, 8, 15, 16, 23, 42])
.enter().append("p")
.text(function(d) {
//d represents each data node in the array
return "I’m number " + d + "!";
});
</script>

In the previous example, a new paragraph <p> element is created (by using .append("p")) for each value with the text saying which number it is.

This can, of course, be extended by creating SVG elements based on the available data:

<html>
<body>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js"></script>
<script>
var svg = d3.select("body").append('svg').attr("width", 1000).attr("height", 1000)

svg.selectAll("circle")
.data([4, 8, 15, 16, 23, 42])
.enter().append("circle")
.attr('cx', 200) //x offset
.attr('cy', 200) //y offset
.attr('r', function(d) { return d })
.style('fill', 'purple')
</script>

The code will create six circles with a radius size which is dependent on its array value. And this is how data visualization is created!

Note we had to select an SVG element first before appending the circles to it, as otherwise, it would not know where to append the circle to and it would not render.

In the current example, our data is fixed, but if it were to dynamically change or update, you would expect circles to be added, or removed, using the exit() method. To create these kinds of interactive data visualizations, a common pattern of update, enter, and exit is used, which can be illustrated as follows:

// update…
var p = d3.select("body")
.selectAll("p")
.data([4, 8, 15, 16, 23, 42])
.text(function(d) { return d; });

// Enter…
p.enter().append("p")
.text(function(d) { return d; });

// Exit…
p.exit().remove();

Using this kind of separation makes it easier to specify what kind of actions to take in each scenario, and also illustrates the power of D3: it lets you transform documents based on data, which includes both creating and destroying objects. Also, once the data has been bound to the document, you can omit the data operator going forward; D3 will retrieve the previously bound data and this allows you to reuse properties without rebinding.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.217.122