DHTMLX Gantt w LWC

Aug 29 2020

Implementuję DHTMLX Gantta Chart w LWC. Próbuję wywołać metodę LWC z funkcji biblioteki Gantta, ale nie działa.

Oto kod:

<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);
}

openModalMetoda nie nazywa, bo thisnie jest ważne odniesienie w bibliotece Gantta. Próbowałem, document.getElementByIdco też nie działa. W jaki sposób mogę to osiągnąć?

Odpowiedzi

4 AnmolKumar Aug 29 2020 at 00:42

Kiedy próbujesz użyć thisw callback functionkontekście zmian i tracisz odniesienie do instancji klasy, przeczytaj tutaj

Stare rozwiązanie polega na przechowywaniu odwołania do this(instancji klasy) w osobnej zmiennej ( selfw przykładzie) i używaniu go w wywołaniu zwrotnym

Nowoczesnym rozwiązaniem jest użycie funkcji Arrow, która nie ma własnego thiskontekstu i odwołuje się do kontekstu klasy

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();
        });
    });
}