有一个任务——将一段可重用的代码插入到一个普通的JS组件中。
class Plane extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
if (!this.rendered) {
this.render();
this.rendered = true;
}
}
render() {
this.innerHTML = plane.innerHTML + plane_styles.innerHTML;
}
}
window.customElements.define('plane-scheme', Plane);
const plane = document.createElement('plane');
plane.className = 'plane';
plane.innerHTML = `...`;
document.body.append(plane);
一切都很好。但是,除了HTML元素本身之外,还必须包含几个信息处理程序函数。到目前为止,我还不太明白如何实现它。我试图在构造函数中创建一个箭头函数,将其作为单独的方法添加-零效果。如何正确实施?
自定义元素课程,所以学习:https://javascript.info/class
customElements.define('a-plane', class extends HTMLElement {
connectedCallback() {
this.innerHTML = `A <span>${this.planetype}</span>`;
this.onclick = (evt) => this.fly();
}
get planetype() { // GETTER
return this.getAttribute("type");
}
set planetype(val) { // SETTER
if(!this.isConnected) console.error("I am not in the DOM yet");
this.setAttribute("type", val);
this.querySelector("span").innerHTML = val;
}
fly() { // METHOD
this.classList.toggle("flying");
}
});
const plane = document.createElement('a-plane');
document.body.append(plane);
plane.planetype = "Airbus"; // set After! the element is in the DOM
a-plane {
display: block;
cursor: pointer;
}
.flying {
background: skyblue
}
a-plane.flying:after {
content: " flying"
}
<a-plane type="Boeing"></a-plane>
<a-plane type="Fokker"></a-plane>