Skip to content

Instantly share code, notes, and snippets.

@natevw
Last active December 19, 2015 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natevw/5979039 to your computer and use it in GitHub Desktop.
Save natevw/5979039 to your computer and use it in GitHub Desktop.
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