DHTMLX Gantt ใน LWC

Aug 29 2020

ฉันกำลังใช้DHTMLX Gantt Chartใน LWC ฉันพยายามเรียกเมธอด LWC จากฟังก์ชันไลบรารีแกนต์ แต่ใช้งานไม่ได้

นี่คือรหัส:

<template>
    <input type="hidden" id="hidden-task-data" onclick={openModal}/>
    <div class="thegantt" lwc:dom="manual" style='width:100%;'></div>
</template>

this.isModalOpen = false;

renderedCallback() {
    Promise.all([
            loadScript(this, DHTMLX7 + '/codebase/dhtmlxgantt.js'),
            loadStyle(this, DHTMLX7 + '/codebase/dhtmlxgantt.css')
    ]).then(() => {
        const root = this.template.querySelector('.thegantt');
        root.style.height = "300px";
        const gantt = window.Gantt.getGanttInstance();

        //This method is called when a user double clicks on a task bar of the chart
        gantt.attachEvent("onTaskDblClick", function(id, e) {
            /* As per LWC's documentation, this doesn't work
            let taskInput = document.getElementById("hidden-task-data");
            taskInput.value = e;
            taskInput.click();
            */
            this.openModal(); //This doesn't work
            return true;
        });
    });
}

openModal() {
    this.isModalOpen = true;
    console.log(this.isModalOpen);
}

openModalวิธีการไม่ได้เรียกว่าเพราะthisไม่ได้มีการอ้างอิงที่ถูกต้องในห้องสมุดแกนต์ ฉันได้ลองdocument.getElementByIdซึ่งใช้งานไม่ได้เช่นกัน มีวิธีใดบ้างที่ฉันจะบรรลุเป้าหมายนี้

คำตอบ

4 AnmolKumar Aug 29 2020 at 00:42

เมื่อคุณพยายามใช้thisในcallback functionบริบทเปลี่ยนไปและคุณอ้างอิงถึงอินสแตนซ์คลาสอย่างหลวม ๆโปรดอ่านที่นี่

วิธีแก้ปัญหาเก่าคือการจัดเก็บการอ้างอิงถึงthis(อินสแตนซ์คลาส) ในตัวแปรแยกต่างหาก ( selfในตัวอย่าง) และใช้ในการเรียกกลับ

โซลูชันที่ทันสมัยคือการใช้ฟังก์ชัน Arrowซึ่งไม่มีthisบริบทของตัวเองและอ้างถึงบริบทของคลาส

renderedCallback() {
    Promise.all([
            loadScript(this, DHTMLX7 + '/codebase/dhtmlxgantt.js'),
            loadStyle(this, DHTMLX7 + '/codebase/dhtmlxgantt.css')
    ]).then(() => {
        const gantt = window.Gantt.getGanttInstance();

        // Using Arrow function
        gantt.attachEvent("onTaskDblClick", (id, e) => {
            this.openModal();
        });

        // Storing reference of this in another variable
        const self = this;
        gantt.attachEvent("onTaskDblClick", function(id, e) {
            self.openModal();
        });
    });
}