我正在嘗試刪除打字稿中的事件偵聽器。我在 if 語句中新增事件監聽器。在 else 語句中,我試圖刪除這些事件監聽器,但由於某種原因它沒有刪除它們。
僅供參考:我有一個按鈕,可以在其中設定布林值(movePick)。如果這是真的那麼我希望能夠移動我的物件。這就是建立事件偵聽器的地方。如果我再次單擊該按鈕,我將無法再移動該物件。這就是我嘗試刪除事件偵聽器的原因。
public moveObject(movePick: boolean, raycaster: THREE.Raycaster): void { const plane = new THREE.Plane(); const pNormal = new THREE.Vector3(0, 1, 0); // plane's normal const planeIntersect = new THREE.Vector3(); // point of intersection with the plane const pIntersect = new THREE.Vector3(); // point of intersection with an object (plane's point) const shift = new THREE.Vector3(); // distance between position of an object and points of intersection with the object let isDragging = false; let dragObject: any; // events const pointermove = (event: PointerEvent) => { const rect = this.canvas.getBoundingClientRect(); const x = event.clientX - rect.left const y = event.clientY - rect.top const pickPosition = { x: 0, y: 0 }; pickPosition.x = (x / this.canvas.clientWidth) * 2 - 1; pickPosition.y = (y / this.canvas.clientHeight) * -2 + 1; raycaster.setFromCamera(pickPosition, this.camera); // console.log("movePICK IN POINTERMOVE",movePick) if (isDragging) { raycaster.ray.intersectPlane(plane, planeIntersect); dragObject.position.addVectors(planeIntersect, shift); } } const mousedown = () => { const intersects = raycaster.intersectObjects(this.scene.children); for (let i = 0; i < this.mesharr.length; i++) { if (intersects[0].object.name == this.mesharr[i].name && intersects[0].object.name != "Rail") { pIntersect.copy(intersects[0].point); plane.setFromNormalAndCoplanarPoint(pNormal, pIntersect); shift.subVectors(intersects[0].object.position, intersects[0].point); isDragging = true; dragObject = intersects[0].object; } } } const pointerup = () => { isDragging = false; dragObject = null; } **if (movePick) { document.addEventListener("pointermove", pointermove); document.addEventListener("mousedown", mousedown); document.addEventListener("pointerup", pointerup); } else { document.removeEventListener("pointermove", pointermove); document.removeEventListener("mousedown", mousedown); document.removeEventListener("pointerup", pointerup); }** }
如果我在新增事件列表的同一個 if 語句中刪除事件列表,它們就會被刪除。但如果再次按一下該按鈕並進入 else 語句,則無法刪除它們。我也在 stackoverflow 中嘗試了幾種解決方案,但都不起作用。
將事件實例儲存到類別欄位中,然後在removeEventListener中呼叫該實例,例如。
現在應該可以了