A partial archive of discourse.wicg.io as of Saturday February 24, 2024.

Class based API for Custom Elements?

trusktr
2016-02-06

It might be nice if we could use ES2015 classes for defining Custom Elements with document.registerElement, as an alternative to having to define the prototype of the new element explicitly. For example, this is the current way:

const div = document.registerElement('something-awesome', {
    prototype: Object.assign(Object.create(HTMLElement.prototype), {
        createdCallback() {
            console.log('created')
        },
        attachedCallback() {
            console.log('attached')
        },
        detachedCallback() {
            console.log('detahced')
        },
        attributeChangedCallback() {
            console.log('attr changed')
        },
    })
})

And this would be the new way:

class SomethingAwesome extends HTMLElement {
    createdCallback() {
        console.log('created')
    }
    attachedCallback() {
        console.log('attached')
    }
    detachedCallback() {
        console.log('detahced')
    }
    attributeChangedCallback() {
        console.log('attr changed')
    }
}

const div = document.registerElement('something-awesome', SomethingAwesome)

Perhaps the name of the element can be inferred from the class name if the class is the first arg as a bonus:

const div = document.registerElement(SomethingAwesome)
jonathank
2016-02-10

Seems shimmable from the syntax given there.however class based construction is already being considered:

I would say that the tag name is better not being inferred by the class.name. it leaves the ability to change the element from the class code based upon tag name rather than bind a whole class definition to an element.

so:

class MyTime extends HTMLElement {
  constructor() {
    if (this.tagName === 'trump-time') {
      this.makeElementGreatAgain()
    }
  }
}
document.registerElement('trump-time', MyTime);
document.registerElement('bernie-time', MyTIme);

It also means the element can be purely usage differences etc.

simevidas
2016-02-13

Last I heard, it’s going to be document.defineElement, which is I think based on Apple’s prototype. That prototype does use ES6 classes. Let’s wait for the next announcement from the browser vendors. Shouldn’t be long.