[英]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.