How to remove drag listener that has been called while dragging?
yxchng opened this issue · 3 comments
I am unable to remove the drag listener while I am dragging the element that call d3.drag(). While removing the drag listener, if I mouseup, the listener will be gone but if I hold the mouse down, drag is still listening and drag event will be fired.
I did an experiment. I have an event listener that listen for a keyboard press that will call on(".drag", null). I drag my element around and press the key. I can continue to drag.
Is this expected? If so, how should I stop the drag listener while dragging?
https://jsfiddle.net/38wtj4y0/33/
This jsfiddle is quite similar. It deletes the element when a key is pressed. However, you will notice that console is still printing "dragging" if you delete while mousedown and never release.
There’s not currently an API to cancel an active drag gesture programmatically; the only way a drag gesture ends is when the behavior receives the expected event (mouseup, touchend, touchcancel). You might be able to cancel a gesture by programmatically dispatching one of these events, but I haven’t tried.
In your drag event listener you could check whether the element was removed (if you expect that to happen), and disable the drag behavior’s listeners like so:
function dragged() {
if (!document.contains(this)) { // Removed!
d3.select(window).on(".drag", null); // Optional.
return;
}
…
}
I can’t think of a clean way to support this automatically. The mousemove listener could check if the mousedown’s target element was removed from the DOM, but there could be a delay between when you remove the DOM element and when a subsequent mousemove is triggered.