Skip to content

Instantly share code, notes, and snippets.

@ctiml
Forked from mbostock/.block
Last active November 10, 2015 13:36
Show Gist options
  • Save ctiml/142fa86a3f37b363ad9d to your computer and use it in GitHub Desktop.
Save ctiml/142fa86a3f37b363ad9d to your computer and use it in GitHub Desktop.
08-General Update Pattern, I
<!DOCTYPE html>
<meta charset="utf-8">
<style>
text {
font: bold 48px monospace;
}
.enter {
fill: green;
}
.update {
fill: #333;
}
.remove {
fill: red;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
var a = "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) {
// 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("x", function(d, i) { return i * 32; })
.attr("dy", ".35em");
// 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.text(function(d) { return d; });
// EXIT
// Remove old elements as needed.
if (data.length == 0) {
text.exit().remove();
} else {
text.exit().attr("class", "remove");
}
}
var next = (function(alphabet){
var _a = alphabet;
var e = 0;
var s = 1;
return function() {
e += 2 * s;
if (e == 26 || e == 0) {
s *= -1;
}
return _a.slice(0, e).sort();
}
})(a);
// The initial display.
//update(alphabet);
update(next());
// Grab a random sample of letters from the alphabet, in alphabetical order.
setInterval(function() {
update(next());
//update(d3.shuffle(alphabet)
// .slice(0, Math.floor(Math.random() * 26))
// .sort());
}, 500);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment