Last active
December 19, 2015 15:48
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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