I'm writing a reusable component, a function that takes a selection g (typically an SVG g element) and draws a chart. The function (done in the standard closure-with-accessors format) can be called multiple times with the same g element but different data. I've found a few places in my code where I want something to happen only the first time the function is called. Here is the best solution I can come up with:
var axis = g.selectAll(".y.axis").data([0]);
axis.enter().append("g").attr("class", "y axis");
axis.call(yAxis);
I don't want more than one y-axis, and so I join to one element. The append operation is only performed the first time. I always want to call yAxis because the scale may have changed. This works, but it seems ugly and is cluttering up my code. Is there a better way? Failing that, is the intent clear from the code?
Any thoughts or feedback appreciated, even if it's just "looks fine to me".