Eyal Kutz
Eyal Kutz

Reputation: 310

how to create a custom element in dart html

I am trying to create a custom element in dart HTML and this answer shows how to do so but it uses a deprecated API so my question is how can I do that today? my code:

class HelloWorld extends HtmlElement {
  static final tag = 'hello-world';
  factory HelloWorld() {
    var self = Element.tag(tag);
    var shadow = self.attachShadow({'mode': 'open'});
    shadow.children = [
      HRElement()..style.width = '50%',
      ParagraphElement()..text = 'hello world',
      HRElement()..style.width = '80%',
    ];
    return self;
  }
  HelloWorld.created() : super.created();
}

void main() {
  document.registerElement(HelloWorld.tag, HelloWorld);
}

the error:

Uncaught Error: Invalid argument(s): HelloWorld
    at Object.throw_ [as throw] (dart_sdk.js:3879)
    at Object._registerCustomElement (dart_sdk.js:98068)
    at HTMLDocument.[dartx.registerElement2] (dart_sdk.js:75054)
    at HTMLDocument.[dartx.registerElement] (dart_sdk.js:70020)
    at main$ (main.dart:19)
    ...

Upvotes: 1

Views: 632

Answers (1)

Daniel V.
Daniel V.

Reputation: 1198

Uff... This one is a hard one.

  1. Document.registerElement is a deprecated API - don't use it. https://developer.mozilla.org/en-US/docs/Web/API/Document/registerElement
  2. Dart's window.customElements.define is half done. There were little interest in this api, so they left it in half-broken state.

Some interesting reading regarding this:

My 2 cents on the issue is that you should be able to write a proper JS interop layer on top of vanilla browser APIs and use it from Dart. However, the custom-element-demo repo shows that there are some things one needs to pay attention to when undertaking such a task.

Upvotes: 1

Related Questions