1

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)
    ...
Eyal Kutz
  • 190
  • 2
  • 13

1 Answers1

1

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Daniel V.
  • 1,138
  • 1
  • 9
  • 15
  • [Seth Ladd has an old post on this](http://blog.sethladd.com/2012/11/your-first-web-component-with-dart.html), maybe it's helpful. – Philippe Fanaro Oct 24 '20 at 20:56