Binding Functions as Data

Primitives and object literals are not the only things you can bind to a D3 visualization. After all, aren’t javascript functions objects as well?

1
2
3
4
5
6
7
8
9
10
var data = [];
var next = function(x) { return 15 + x*x };
var newData = function() { data.push(next); return data; }
var selection = d3.select("#container")
                  .selectAll("div")
                  .data(newData);

...
                  .select("#span")
                    .text(function(d, i) { return d(i); });

If you provide a function to the data function, D3 will simply invoke the function and use the returned value as a parameter of the data function.

Resources

Data Visualization with D3.js Cookbook (affiliate link)