Create a gist now

Instantly share code, notes, and snippets.

A helper to avoid configuration property accessor boilerplate when creating D3 "reusable chart"–style widgets.
// helper for <http://bost.ocks.org/mike/chart/#reconfiguration>
function _makeChart() {
var state = Object.create(null),
viz = this.bind(state);
Array.prototype.slice.call(arguments).forEach(function (k) {
viz[k] = function (v) {
if (!arguments.length) return state[k];
state[k] = v;
return viz;
};
});
return viz;
}
// --- example usage ---
// define a (really simple) resuable chart
var chartFactory = _makeChart.bind(function (sel) {
var scale = d3.scale.linear().range([0,this.foo]);
sel.text(function (d) { return "Scaled value is: " + scale(d); });
}, 'foo', 'bar');
// use it like any other…
var myChart = chartFactory().foo(42).bar('none');
d3.select(container).selectAll('.the.things').data([1,-1,Math.PI]).call(function (sel) {
sel.enter().append('p').classed('the', true).classed('things', true);
sel.exit().remove();
sel.call(myChart); // (usually chart would draw small multiples using *nested* arrays)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment