Skip to content

Instantly share code, notes, and snippets.

@lmatteis
Forked from mbostock/.block
Last active April 3, 2016 17:28
Show Gist options
  • Save lmatteis/0a11aa639095e888a01f7972056d38c9 to your computer and use it in GitHub Desktop.
Save lmatteis/0a11aa639095e888a01f7972056d38c9 to your computer and use it in GitHub Desktop.
General Update Pattern, I
license: gpl-3.0

This example demonstrates the general update pattern in D3, where a data-join is followed by operations on the enter, update and exit selections. Entering elements are shown in green, while updating elements are shown in black. Exiting elements are removed immediately, so they're invisible.

This example does not use a key function for the data-join, so entering elements are always added to the end: when the new data has more letters than the old data, new elements are entered to display the new letters. Likewise, exiting letters are always removed from the end when the new data has fewer letters than the old data.

Next: Key Functions

<!DOCTYPE html>
<meta charset="utf-8">
<style>
text {
font: bold 48px monospace;
}
.enter {
fill: green;
}
.update {
fill: #333;
}
</style>
<body>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script>
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
var width = 960,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
//.attr("transform", "translate(32," + (height / 2) + ")");
// create a button
var button = d3
.select('body')
.append('button')
.text('update')
.on('click', function () {
update(d3.shuffle(alphabet)
.slice(0, Math.floor(Math.random() * 26))
.sort())
//update(['a', 'b', 'c'])
})
function update(data) {
// DATA JOIN
// Join new data with old elements, if any.
var text = svg.selectAll("text")
.data(data, function(d) { return d; });
// UPDATE
// Update old elements as needed.
text.attr("class", "update");
// ENTER
// Create new elements as needed.
text.enter().append("text")
.attr("class", "enter")
.attr("dy", ".35em")
.text(function(d) { return d; });
// ENTER + UPDATE
// Appending to the enter selection expands the update selection to include
// entering elements; so, operations on the update selection after appending to
// the enter selection will apply to both entering and updating nodes.
text.attr("x", function(d, i) { return Math.floor(Math.random() * width) ; })
text.attr("y", function(d, i) { return Math.floor(Math.random() * height) ; })
// EXIT
// Remove old elements as needed.
text.exit().remove();
}
// The initial display.
update(alphabet);
// Grab a random sample of letters from the alphabet, in alphabetical order.
// setInterval(function() {
// update(d3.shuffle(alphabet)
// .slice(0, Math.floor(Math.random() * 26))
// .sort());
// }, 1500);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment