Skip to content

Instantly share code, notes, and snippets.

@dehowell
Forked from mbostock/.block
Last active August 29, 2015 14:15
Show Gist options
  • Save dehowell/e255bbd54897577b180e to your computer and use it in GitHub Desktop.
Save dehowell/e255bbd54897577b180e to your computer and use it in GitHub Desktop.
General Update Pattern, II - Broken for Educational Purposes

This is a deliberately broken fork of Mike Bostock's "General Update Pattern, II". Please see the original for an explanation of what's supposed to be happening. I've increased the pause between updates and switched to the default key function to illustrate how D3 calculates the enter, update, and exit selections. Open the console to see the data for each update.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
text {
font: bold 48px monospace;
}
.enter {
fill: green;
}
.update {
fill: #333;
}
</style>
<body>
<script src="http://d3js.org/d3.v2.min.js?2.10.1"></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) + ")");
function update(data) {
console.log(data.join(""));
// DATA JOIN
// Join new data with old elements, if any.
var text = svg.selectAll("text")
.data(data);
// 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 i * 32; })
// 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(shuffle(alphabet)
.slice(0, Math.floor(Math.random() * 26))
.sort());
}, 5000);
// Shuffles the input array.
function shuffle(array) {
var m = array.length, t, i;
while (m) {
i = Math.floor(Math.random() * m--);
t = array[m], array[m] = array[i], array[i] = t;
}
return array;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment