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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.