While learning D3.js, I have come across the blog post explaining the main design-pattern behind it's reusable units of code. I have reproduced the relevant bit of code below. The way the pattern is presented below is exactly the way it is used in D3 codebase and plug-ins (example).
My one issue with this code is that it has so much copy-paste for the properties. JavaScript being a functional language, I thought I'd be able to re-factor the boilerplate code out, but I can't think of a way to do it. The arguments
and value
parameters are easy to pass to a common function, but I can't find a way to preserve a reference to the width
and height
properties.
function chart() {
var width = 720, // default width
height = 80; // default height
function my() {
// generate chart here, using `width` and `height`
}
my.width = function(value) {
if (!arguments.length) return width;
width = value;
return my;
};
my.height = function(value) {
if (!arguments.length) return height;
height = value;
return my;
};
return my;
}
The fact that this is how it's done in the actual D3 codebase, makes me wonder if re-factoring is possible, but I'm hoping that it's simply a matter of this not being a high priority issue (and new contributors are doing it this way, because that's how it was done before).
What I'm looking for is basically replacing every accessor's body with:
my.height = function(value) {
return getSet(arguments, value, whatever);
};
There is still some boilerplate for the call, but at least the logic is centralized and can be updated in only one place, if needed.