Data Joins and
Update Patterns in D3
Objectives
-
Join data to a d3 selection using the data method
-
Target nodes to append to the DOM via the enter selection
-
Target nodes to remove from the DOM via the exit selection
-
Perform more advanced data joins by using a key function
-
Update existing DOM elements with new data
-
Merge update and enter selections, and describe D3's general update pattern
Basic Data Joins and Enter Selections
Data Joins in D3
<ul>
<li></li>
<li></li>
<li></li>
</ul>
var data = [
{ key: 'value' },
{ key: 'another value' },
{ key: 'third value' },
];
Code Example
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Data Joins with D3</title>
</head>
<body>
<h1>Movie quotes.</h1>
<ul id="quotes">
</ul>
<script src="https://d3js.org/d3.v4.js"></script>
<script src="app.js"></script>
</body>
</html>
Code: http://bit.ly/2sgjAf5
Live Site: http://bit.ly/2s6d0cy
Understanding Data Joins
DOM
JS
<ul id="quotes">
</ul>
var quotes = [
{ /* ... */ },
{ /* ... */ },
{ /* ... */ },
{ /* ... */ },
{ /* ... */ }
];
.__data__
.enter()
selection.enter
<ul id="quotes">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
.append("li")
Callback Structure
function (d, i) {
// write your code here
}
Index of the current element in the selection.
Data bound to the current element.
Understanding Data Joins
d3.select('#quotes')
.style('list-style', 'none')
.selectAll('li')
.data(quotes)
.enter()
.append('li')
.text(function(d) {
return d.quote;
});
data bound to current element
Exit Selections and Key Functions
Code Example
Code: http://bit.ly/2rwwxV4
Live Site: http://bit.ly/2rlHqFc
Exit Selections
nonRQuotes.length; // 3
nonRQuotes[0];
nonRQuotes[1];
nonRQuotes[2];
Exit
Key Functions
selection.data(dataArr [, keyFunction])
Return value used to join elements and data
Exit Selections
nonRQuotes.length; // 3
nonRQuotes[0];
nonRQuotes[1];
nonRQuotes[2];
Exit
General Update Pattern
Code Example
Code: http://bit.ly/2sgvRQL
Live Site: http://bit.ly/2t7ZyDR
Selection Types
Enter
(data with no elements)
Exit
(elements with no data)
Update
(data +
elements)
Merging Selections
selection.merge(otherSelection)
Merges selection and otherSelection together into a new selection.
General Update Pattern
-
Grab the update selection, make any changes unique to that selection, and store the selection in a variable.
-
Grab the exit selection and remove any unnecessary elements.
-
Grab the enter selection and make any changes unique to that selection.
-
Merge the enter and update selections, and make any changes that you want to be shared across both selections.
YOUR
TURN
Data Joins and Update Patterns in D3
By Elie Schoppik
Data Joins and Update Patterns in D3
Introduction to DOM manipulation with D3
- 2,211