[英]How to define global constant when creating Web component?
I am creating custom web component "upload-widget", and declaring three constants in constructor to be referenced in functions later:我正在创建自定义 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);
This code fails since Javascript does not recognize the declared constants in the "connectedCallback()" nor in the function "upload_action()".此代码失败,因为 Javascript 无法识别“connectedCallback()”和 function“upload_action()”中声明的常量。 Moving the declaration to either of the functions makes the constants valid only for the function scope, not beyond.将声明移动到任一函数使常量仅对 function scope 有效,而不是超出。 How do I declare constant/variable valid for the whole scope of the class including functions?如何声明对 class 的整个 scope (包括函数)有效的常量/变量?
you need to declare them as class variables, so your constructor
would look like:您需要将它们声明为 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");
};
Later in the code you can access them as this.UPLOAD_BUTTON
.稍后在代码中,您可以通过this.UPLOAD_BUTTON
访问它们。
Advice: Try to use camelCase when naming variables, it looks more "javascripty".忠告:命名变量时尽量使用camelCase,看起来更“javascripty”。 So instead of this.UPLOAD_BUTTON
write this.uploadButton
.所以代替this.UPLOAD_BUTTON
写this.uploadButton
。
Note your template use is a bit bloated, you can do:请注意,您的模板使用有点臃肿,您可以这样做:
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.