如何在 Dart 中创建 Web 组件

Phi*_*aro 7 html javascript dart angular-dart

1. 背景

\n

在 vanilla JS 中可以通过以下方式创建 Web 组件:

\n
    \n
  1. 创建一个类extends HTMLElement
  2. \n
  3. 然后注册它:\n
    window.customElements.define(\'app-drawer\', AppDrawer);\n
    Run Code Online (Sandbox Code Playgroud)\n
  4. \n
\n

由于我在 Dart 中有很多代码,我想我可以用它来做到这一点。但我遇到了一些障碍。主要是已被弃用且似乎不起作用的事实document.registerElement()window.customElements.define()

\n
\n

I mostly use Microsoft Edge as a browser. But it uses Chromium anyway. And I\'ve also tested everything mentioned below on Chrome as well.

\n
\n

2. What I\'ve Tried

\n

2.1. G\xc3\xbcnter\'s Answer with document.registerElement()

\n

G\xc3\xbcnter\'s answer points to this dartpad, which uses the document.registerElement() to define it.

\n

His answer does work, but document.registerElement() is deprecated:

\n
document.registerElement is deprecated and will be removed in M80, around February 2020. Please use window.customElements.define instead.\n
Run Code Online (Sandbox Code Playgroud)\n

Or at least on my computer it works, because his DartPad actually gives back the error of NoSuchMethodError: method not found: \'registerElement\'

\n

2.2 Trying the same thing with window.customElements.define()

\n
\n

My DartPad

\n
\n
\n

My Gist

\n
\n
document.registerElement is deprecated and will be removed in M80, around February 2020. Please use window.customElements.define instead.\n
Run Code Online (Sandbox Code Playgroud)\n

The code above will yield the following error message:

\n
Error: Failed to execute \'define\' on \'CustomElementRegistry\': The callback provided as parameter 2 is not a function.\n
Run Code Online (Sandbox Code Playgroud)\n

2.3. An Attempt with JS Interop

\n

I\'ve even tried to create an interop function for JS\'s window.customElements.define, but the error was the same.

\n
import \'dart:html\';\n\nmain() {\n  try {\n    window.customElements.define(\'graph-button\', GraphButton);\n    final GraphButton button = GraphButton();\n    document.body.append(button);\n    button.changeInnerHtml();\n  } catch (e) {}\n}\n\nclass GraphButton extends HtmlElement {\n  static const String tag = \'graph-button\';\n\n  factory GraphButton() => Element.tag(GraphButton.tag);\n\n  GraphButton.created() : super.created();\n\n  changeInnerHtml() => innerHtml = \'foo\';\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Then simply replacing the registering above for registerWebComponent(GraphButton.tag, GraphButton); will now yield the same error message.

\n

3. Other Helpful Resources

\n

Is there official documentation on this topic? I was hoping to find something about it on AngularDart\'s docs \xe2\x80\x94 since, in Angular, creating web components is quite common \xe2\x80\x94, but I haven\'t been able to so far.

\n\n