Things you might want to know about D3.js

Like jQuery, the interface is method chaining, except when it isn’t. You can do this, for example:

1
d3.selectAll('p').style('color', 'blue').data('i-am-a-blue-paragraph').append('a');
d3.selectAll('p').style('color', 'blue').data('i-am-a-blue-paragraph').append('a');

but this will give you a different result:

1
d3.selectAll('p').append('a').style('color', 'blue').data('i-am-a-blue-paragraph');
d3.selectAll('p').append('a').style('color', 'blue').data('i-am-a-blue-paragraph');

Some methods return the original selection, but others change it. data() and style() don’t change your selection, but append() and enter() do. This wouldn’t be a problem if each method in the chain didn’t visually look exactly the same, but since they do, you just have to use your instinct to determine what a method returns (which should usually be right), and look it up when you’re not sure.

You might prefer the explicitness of something like:

1
2
var allP = d3.selectAll('p').style('color', 'blue').data('i-am-a-blue-paragraph');
var a = allP.append('a');
var allP = d3.selectAll('p').style('color', 'blue').data('i-am-a-blue-paragraph');
var a = allP.append('a');

Leave a Reply

Your email address will not be published. Required fields are marked *