当我们使用聚合物或 x-tag 时,我们必须注册一个新元素。但是为什么,如果我们可以使用普通的 es6 javascript 来构建一个不带 registerElement 的隐藏组件。这在最新版本的 Chrome、Firefox 和 Edge 中运行良好,无需 polyfill 或转译为 es5。
<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 Components – 一个没有框架的人
和元素注册:
在使用自定义元素之前,需要对其进行注册。否则,浏览器会将其视为 HTMLElement。意义 ?
更新- W3C 规范于 2016 年 3 月 18 日更新:
来自2.1的介绍:
自定义元素为作者提供了一种构建自己的功能齐全的 DOM 元素的方法。尽管作者总是可以在他们的文档中使用非标准的标签名称,并在事后通过脚本或类似的方式添加特定于应用程序的行为,但这些元素在历史上一直是不合规的并且不是很实用。通过定义自定义元素,作者可以告知解析器如何正确构造元素以及该类的元素应如何对更改做出反应。