DHTMLX Gantt trong LWC
Tôi đang triển khai Biểu đồ Gantt DHTMLX trong LWC. Tôi đang cố gắng gọi một phương thức LWC từ hàm thư viện gantt nhưng nó không hoạt động.
Đây là mã:
<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);
}
Các openModalphương pháp không được gọi vì thiskhông phải là một tài liệu tham khảo có giá trị trong thư viện đồ Gantt. Tôi đã thử document.getElementByIdmà cũng không hoạt động. Những cách tôi có thể đạt được điều này là gì?
Trả lời
Khi bạn cố gắng sử dụng thistrong một callback functionngữ cảnh thay đổi và bạn mất tham chiếu đến cá thể lớp, hãy đọc ở đây
Giải pháp cũ là lưu trữ một tham chiếu tới this( Cá thể lớp) trong một biến riêng biệt ( selftrong ví dụ) và sử dụng nó trong lệnh gọi lại
Giải pháp hiện đại là sử dụng hàm Arrow không có thisngữ cảnh riêng và tham chiếu đến ngữ cảnh lớp
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();
});
});
}