LWC의 DHTMLX Gantt

Aug 29 2020

LWC에서 DHTMLX Gantt Chart 를 구현하고 있습니다. 간트 라이브러리 함수에서 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();
        });
    });
}