d3js General Update Pattern, I 读书笔记

虽然叫数据绑定,但是仅仅是数据发生了变化,并不会让d3操作的dom发生变化,还是得自己来操作.

比如如下的脚本,看着就清楚了

<!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) {

  // 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.
  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());
}, 1500);

// Shuffles the input array.
function shuffle(array) {
  var m = array.length, t, i;
  while (m) {
    i = Math.floor(Math.random() * m--);
    t = array![pic](m), array![pic](m) = array![pic](i), array![pic](i) = t;
  }
  return array;
}

</script>