[英]How to define global constant when creating Web component?
我正在创建自定义 web 组件“upload-widget”,并在构造函数中声明三个常量,以便稍后在函数中引用:
const template = document.createElement('template');
template.innerHTML = `
<div id="dropper-zone">
<input type="file" name="file_input" id="file_name">
<button type="button" id="upload_btn">Upload</button>
<div id="upload_status"></div>
</div>
`;
class UploadWidget extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(template.content.cloneNode(true));
const FILE_NAME = this.shadowRoot.getElementById("file_name");
const UPLOAD_BUTTON = this.shadowRoot.getElementById("upload_btn");
const UPLOAD_STATUS = this.shadowRoot.getElementById("upload_status");
};
upload_action() {
if (!FILE_NAME.value) {
console.log("File does not exists");
return;
UPLOAD_STATUS.innerHTML = 'File Uploaded';
};
connectedCallback() {
UPLOAD_BUTTON.addEventListener("click", () => this.upload_action());
}
}
customElements.define('upload-widget', UploadWidget);
此代码失败,因为 Javascript 无法识别“connectedCallback()”和 function“upload_action()”中声明的常量。 将声明移动到任一函数使常量仅对 function scope 有效,而不是超出。 如何声明对 class 的整个 scope (包括函数)有效的常量/变量?
您需要将它们声明为 class 变量,因此您的constructor
如下所示:
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(template.content.cloneNode(true));
this.FILE_NAME = this.shadowRoot.getElementById("file_name");
this.UPLOAD_BUTTON = this.shadowRoot.getElementById("upload_btn");
this.UPLOAD_STATUS = this.shadowRoot.getElementById("upload_status");
};
稍后在代码中,您可以通过this.UPLOAD_BUTTON
访问它们。
忠告:命名变量时尽量使用camelCase,看起来更“javascripty”。 所以代替this.UPLOAD_BUTTON
写this.uploadButton
。
请注意,您的模板使用有点臃肿,您可以这样做:
constructor() {
let html = `
<div id="dropper-zone">
<input type="file" name="file_input" id="file_name">
<button type="button" id="upload_btn">Upload</button>
<div id="upload_status"></div>
</div>`;
super() // sets AND returns this scope
.attachShadow({mode: 'open'}) // sets AND returns this.shadowRoot
.innerHTML = html;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.