binding functions as data

February 27, 2014

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?

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)


Katie Leonard

Mostly Katie explaining things to herself.

© 2025