I'm working on a framework to make d3 less fragile. So I have class called Phrase that basically passes through "d3 operator methods". Hope you are familiar with d3 terminology for that to make sense. But this is really a question about Javascript.
It looks like this (inside of base class Phrase):
class Phrase {
exit(selection, transition) {
// make sure nothing flaky is going on
this._assert(selection, transition)
const s = selection.exit()
//mutate selection
this._finishSelection(s, "exit")
return s
}
_finishSelection(s, method) {
function(mutate) {
s._kind = method
s._select = s.select; s.select = select
}
function select(selector) {
const ns = s._select(selector)
mutate(ns)
return ns
}
mutate(selection)
}
}
So the super class calls this base class and does sanity checks and then adds a little info about the context it was created in. But it really just passes through what d3 does. And this is the design to not get very involved but just record.
This works but:
- There is a handful of methods I need to override. I could wrap the method override into a function and I will if this the only option.
- I want this to be decoupled as possible. d3 shou ld do its thing without me messing around with instances. I have to. And it should be a minimal as possible.
- There is a possibility of overriding the Selection class itself but it is not exported.
Things like this I believe can be looked at many different ways. So this is my way of believing, but can it be done better? I want the least amount of dark magic as possible but at the same time d3 was not meant to be subclassed.