How to add method for grouped selection?
See original GitHub issueA simple question relating to the project structure that I have not been able to figure it out for the life of me.
If I want to add a method to selection
that works on both plain selections and grouped selections how do I do that?
As an example I have this function for short-handing transitions:
d3.selection.prototype.move_to = function ({ x = 0, y = 0 }) {
const eval_pos = function (p) {
if (typeof p === "function") {
return p(this.datum());
} else {
return p;
}
};
return this.attr("transform", `translate(${eval_pos(x)},${eval_pos(y)})`);
};
It works great on simple selections. E.g.
svg.select('g').move_to({x:margin.left,y:margin.top});
But not on grouped selections:
svg.selectAll('g.chart_elements').move_to({x:x_pos,y:y_pos});
I tried adding the prototype to d3.selectionAll
but that didn’t work either.
Clearly I am attaching the prototype to the wrong object but I can’t figure out what the correct object type is as I only see one call to the prototype assignment here.
It looks like Selection
is the proper object but I don’t see that getting exported as its prototypes just get merged with selection
and then selection
is exported. Is this correct and there’s no way to add a prototype to the group selection when operating on the bundled code?
Thanks and I hope this is the appropriate area for this question!
Best, Nick
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (3 by maintainers)
So you want to allow x and y to be specified as separate arguments? You might instead consider something like this:
Or more simply, since d is already in the right shape:
This could then be implemented as:
If you want x and y to be specified as separate functions, you have to decide whether you want to compute all the x-values first and then all the y-values, or if you want to interleave the computation. But I think it’s simpler if you only allow the function to be at the top level, rather than allowing an object-of-functions.
If that’s what you want, you can simplify like so: