मैं कस्टम वेब घटक "अपलोड-विजेट" बना रहा हूं, और बाद में कार्यों में संदर्भित करने के लिए कन्स्ट्रक्टर में तीन स्थिरांक घोषित कर रहा हूं:
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);
यह कोड विफल रहता है क्योंकि जावास्क्रिप्ट "कनेक्टेड कॉलबैक ()" में घोषित स्थिरांक को नहीं पहचानता है और न ही "अपलोड_एक्शन ()" फ़ंक्शन में। घोषणा को किसी भी फ़ंक्शन में ले जाना स्थिरांक को केवल फ़ंक्शन स्कोप के लिए मान्य बनाता है, इससे आगे नहीं। मैं कार्यों सहित कक्षा के पूरे दायरे के लिए स्थिर/चर को वैध कैसे घोषित करूं?
2 जवाब
आपको उन्हें वर्ग चर के रूप में घोषित करने की आवश्यकता है, इसलिए आपका 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
के रूप में एक्सेस कर सकते हैं।
सलाह: चर नामकरण करते समय कैमलकेस का उपयोग करने का प्रयास करें, यह अधिक "जावास्क्रिप्टी" दिखता है। इसलिए 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;
}