编写 Web 组件类的 ES5 方法是什么?



要定义自定义 Web 组件,我们可以扩展 ES6 类以访问元素的生命周期反应

class HelloElement extends HTMLElement {
// Monitor the 'name' attribute for changes.
static get observedAttributes() {return ['name']; }
// Respond to attribute changes.
attributeChangedCallback(attr, oldValue, newValue) {
if (attr == 'name') {
this.textContent = `Hello, ${newValue}`;
}
}
}
// Define the new element
customElements.define('hello-element', HelloElement);

ES5 的等效方法是什么?

根据您的评论,我假设您的意思是 ES6语法,并且允许支持自定义元素的浏览器也支持的 ES6 定义的函数。

为了模拟调用super()的默认 ES6 构造函数,我们可以使用Reflect.construct来调用HTMLElement构造函数,但使用我们HelloElement构造函数的原型。

对于继承,您需要将HelloElement构造函数的.prototype设置为HTMLElement的实例,并在其上定义方法和属性。通常使用 usingObject.create()创建非功能性虚拟实例,而无需在此处调用构造函数。

您可以使用Object.defineProperty来定义observedAttributes的静态getter,但它通常只是一个静态列表,您可以简单地将HelloElement.observedAttributes设置为属性名称数组。

function HelloElement() {
return Reflect.construct(HTMLElement, [], HelloElement);
}
HelloElement.prototype = Object.create(HTMLElement.prototype);
// Monitor the 'name' attribute for changes.
Object.defineProperty(HelloElement, 'observedAttributes', {
get: function() { return ['name']; }
});
// or just use HelloElement.observedAttributes = ['name']
// if it doesn't need to be dynamic
// Respond to attribute changes.
HelloElement.prototype.attributeChangedCallback = function(attr, oldValue, newValue) {
if (attr == 'name') {
this.textContent = `Hello, ${newValue}`;
}
}
customElements.define('hello-element', HelloElement);
setTimeout(function() {
document.getElementById('example').setAttribute('name', "World");
}, 1000);
<hello-element id="example"></hello-element>

没有编写 Web 组件类的 ES5 方法。Web 组件需要 ES6 功能,这是没有办法的。如果因为转译器不发出而无法使用 ES6class语法,则至少需要使用 ES6Reflect.construct来使用自己的原型创建自定义元素。

或者,自定义元素 polyfill 似乎适用于 ES5 类,至少在大多数浏览器中是这样。

对于 ECMAScript 5 及更低版本的 DOM 节点,它并不是非常有效。如果您愿意,您可以添加到主机原型中,但您不会获得实际的、干净的子类。

这就是为什么对象包装器有时用于 DOM 元素的原因。

您可以使用Reflect方法来执行此操作,但这是 ES6 的功能。

function CustomElement() {
return Reflect.construct(HTMLElement, [], CustomElement);
}
Object.setPrototypeOf(CustomElement.prototype, HTMLElement.prototype);
Object.setPrototypeOf(CustomElement, HTMLElement);
customElements.define('custom-element', CustomElement);
var elem = document.createElement('custom-element');
document.body.appendChild(elem);

这会将<custom-element></custom-element>附加到body

相关内容

最新更新