WebReflection / fix-babel-class

A runtime one-off fix for Babel transpiled classes
ISC License
6 stars 0 forks source link

Illegal Invocation when calling super methods of subclass ancestors #1

Open shennan opened 7 years ago

shennan commented 7 years ago

It seems the context of the object is lost somewhere in calling an ancestor's methods.

class A extends HTMLElement {
  empty () {
    while (this.hasChildNodes()) {
      this.removeChild(this.lastChild)
    }
  }
}
class B extends A {
  constructor () {
    super()
    this.empty()
  }
}

customElements.define('b-element', B)

fixBabelClass(A)
fixBabelClass(B)

let b = new B()

As an illustration, note how Chrome prints my b custom element when transpiling/fixing-class, as opposed to native ES6 Chrome.

Babel + Fix-Babel-Class

screen shot 2017-06-06 at 17 24 09

Native ES6

screen shot 2017-06-06 at 17 23 01
WebReflection commented 7 years ago

try this instead:

class B extends A {
  constructor () {
    super().empty();
  }
}
WebReflection commented 7 years ago

actually, no.

There are few things here that could go wrong.

To start with the first one, you cannot patch after registering the class, it's impossible to overwrite the registry.

this is upside down

customElements.define('b-element', B)

fixBabelClass(A)
fixBabelClass(B)

do this instead

fixBabelClass(A)
fixBabelClass(B)

customElements.define('b-element', B)

Secondly, if you are not using a polyfill upfront nothing will ever work.

You need document-register-element or any other polyfill that works to use Babel and custom elements because these need to patch HTMLElement.

If you have done both things and you still have problems please let me know.