I’m reading through this tutorial on reusable charts in d3, and in the first “Configuration” section, the author describes two ways of making a chart function:
// Method 1
function chart(config) {
// generate chart here, using `config.width` and `config.height`
}
// Method 2
function chart(config) {
return function() {
// generate chart here, using `config.width` and `config.height`
};
}
He suggests the second method over the first, because
However, the caller must then manage both the chart function (assuming you have multiple types of charts to pick from) and the configuration object. To bind the chart configuration to the chart function, we need a closure.
I don’t understand this explanation, though. What are the advantages of method 2 over the first method?
It’s about managing information. In the first case, if you want to change the configuration of the chart, the caller has to remember that
confighas to be passed tochart:Now, if there are multiple, potentially different, charts (and therefor different chart functions, like
barchart,linechart, etc), the caller has to remember which configuration to pass to which function.It would be easier if the “type” of the chart would be self-contained somehow. In the second example, you get back a reference to a function which knows how to update the chart you just created. So you can update the chart without knowing which function it was created by:
This seems to be an approach that D3 uses, but you could also use an object-oriented approach, i.e. creating a proper
Chartconstructor function which encapsulates the logic to render and update a chart.