0

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:

    1. 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.
    1. 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.
    1. 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.

user17130
  • 241
  • 1
  • 6
  • 1
    I've never had a chance to play with it so I don't know how well it would work but perhaps `Proxy` might be a good fit. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy I think this will allow you to generically access properties, as you use it... so you don't need to concretely redefine all your d3 methods. – Norman Breau Feb 16 '19 at 02:56
  • 1
    I think you just got it. +1. Motion to withdraw the question. – user17130 Feb 16 '19 at 03:06
  • 1
    Literally came across `Proxy` the other day and thought "huh that is neat..." But I had trouble thinking of a real use case for it haha. – Norman Breau Feb 16 '19 at 03:22
  • [Is it possible to redefine a JavaScript class's method?](https://stackoverflow.com/questions/21243790/is-it-possible-to-redefine-a-javascript-classs-method) – cantuket Feb 16 '19 at 03:23

0 Answers0