LWCのDHTMLXガント
Aug 29 2020
LWCにDHTMLXガントチャートを実装しています。ganttライブラリ関数から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();
});
});
}