This example shows two improvements to the General Update Pattern in D3 4.0. (The old pattern still works, but the new one is slightly more concise, efficient, and precise.)
The text elements only need to be selected once, when they are created, rather than for every update. That’s because selection.data now modifies the selection in-place:
// DATA JOIN
// Join new data with old elements, if any.
text.data(data, function(d) { return d; });The transition timing parameters don’t need to be repeated for enter, update, and exit. Instead, a top-level transition sets the duration, and then subsequent transitions use selection.transition, passing in t to inherit timing:
var t = d3.transition()
.duration(750);(In fact, this fixes a bug in the 3.x pattern, where occasionally the transitions would be out-of-sync by a millisecond or two. In 4.0, transitions scheduled simultaneously are automatically synchronized using d3.now, even if you don’t explicitly pass a transition to selection.transition! This example also uses the new d3.interval to ensure that no transitions are run when the page is backgrounded.)