我正在尝试删除打字稿中的事件侦听器。我在 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中调用该实例,例如。
现在应该可以了