ポリマーまたは x-tag を使用する場合、新しい要素を登録する必要があります。しかし、プレーンな es6 JavaScript を使用して、registerElement を使用せずに怪しげなコンポーネントを構築できるとすれば、それはなぜでしょうか。これは、ポリフィルや es5 へのトランスパイルなしで、最新バージョンの Chrome、Firefox、および Edge で正常に動作します。
<a-custom-element id="aid"></a-custom-element>
<template id="a-custom-element">
.... // html
</template>
この関数を使用して、コンポーネント クラス インスタンスを初期化 (マウント) します。
function mountCustomElement(custom_tag, custom_class) {
Array.from(document.querySelectorAll(custom_tag)).forEach((element) => {
new custom_class(element, custom_tag);
});
}
document.addEventListener("DOMContentLoaded", function () {
....
mountCustomElement('a-custom-element', AComponent);
....
});
コンポーネント クラス:
class AComponent { // without the extend HTMLElement !!
constructor(custom_element, template_id) {
this.id = custom_element.id;
let content = document.querySelector(`#${template_id}`).content;
// for easy inspection
AComponent.hasOwnProperty('instances') ?Acomponent.instances.push(this) :AComponent.instances = [this];
....
let $root = document.querySelector(`#${this.id}`);
$root.appendChild(document.importNode(content, true));
....
}
参照: ES6 Web コンポーネント – フレームワークのない男
および要素登録:
カスタム要素を使用する前に、登録する必要があります。それ以外の場合、ブラウザーはそれを HTMLElement と見なします。意味 ?
更新- W3C 仕様は本日 2016 年 3 月 18 日に更新されました。
2.1の紹介から:
カスタム要素は、作成者が完全な機能を備えた独自の DOM 要素を構築する方法を提供します。作成者は文書内でいつでも非標準のタグ名を使用でき、アプリケーション固有の動作が事後にスクリプトなどによって追加されますが、そのような要素は歴史的に非準拠であり、あまり機能的ではありませんでした。カスタム要素を定義することにより、作成者は、要素を適切に構築する方法と、そのクラスの要素が変更にどのように反応するかをパーサーに通知できます。