-
Notifications
You must be signed in to change notification settings - Fork 87
what are lifecycle events
The term 'lifecycle events' is used to describe what are otherwise known as joins in d3. Specifically, when new data is added to your visualization, existing data is updated or data is removed, those are lifecycle events.
This concept is somewhat confusing, so we're going to work through an example together.
Consider the code below. It renders a set of circles along the x axis like so:
var chart = d3.select("#vis").append("svg");
var circles = chart.selectAll("circle");
function draw(data, color) {
circles = chart.selectAll("circle")
.data(data, function(d) { return d; });
// UPDATE
circles.style("fill", color)
.attr("r", 5);
// ENTER
circles.enter()
.insert("circle")
.attr("r", 3)
.style("fill", "green");
// MERGE
circles
.attr("cy", 10)
.attr("cx", function(d) {
return d*10;
});
// EXIT
circles.exit()
.style("fill", "grey")
.attr("r", 2);
}
draw([2,4,7,8,9,12,14,15,18], "blue");
Several things are happening as part of that code:
-
When the
draw
function is called, existing elements will be painted the color we pass the draw method (in our example, .) -
Then new elements will be created as circles, with their radius set to 3 and their fill set to .
-
The updated elements AND the new elements get positioned at 10 on the
y
axis and at their value * 10 on thex
axis. -
Elements that are no longer in the data are colored and their radius is made small.
When we call the above draw method the second time with a different data array like so:
draw([1,2,4,5,6,7,8,9,20,21], "blue");
The result clearly shows the above 4 steps:
You can see the live code in this jsBin or a more animated version in this jsBin, but let's step through what is happening in that first and second call:
State of Data Elements | Code Run | Which parts of `draw` are called? |
```javascript
var chart = d3.select("#vis")
.append("svg");
var circles = chart
.selectAll("circle");
|
||
```javascript draw( [2,4,7,8,9,12,14,15,18], "blue" ); ``` |
```javascript
// ENTER
circles.enter()
.insert("circle")
.attr("r", 3)
.style("fill", "green");
|
|
```javascript draw( [1,2,4,5,6,7,8,9,20,21], "blue" ); ``` | ```javascript // UPDATE existing circles from // previous run. color them blue. circles.style("fill", color) .attr("r", 5); ``` | |
```javascript // ENTER render new circles with // appropriate dimensions at the // right place. circles.enter() .insert("circle") .attr("r", 3) .style("fill", "green"); ``` | ||
```javascript // MERGE - both existing and new // circles are now merged - set // their y position and x position // in case they moved circles .attr("cy", 10) .attr("cx", function(d) { return d*10; }); ``` | ||
```javascript // EXIT - for data that is // no longer color its circles // a grey and make it smaller. circles.exit() .style("fill", "grey") .attr("r", 2); ``` |