问题
Converting a D3.js forcediagram from version 5 to 6.1, I write:
let drag = simulation => {
function dragstarted(event, d) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event,d) {
d.fx = event.x;
d.fy = event.y;
}
function dragended(event,d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
// release of fixed positions
function dblclick(d) {
d.fx = null;
d.fy = null;
}
return d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended)
.on("dblclick", dblclick);
However, I am getting the error on dblclick: Uncaught (in promise) Error: unknown type: dblclick d3.min.js:2:9279
The code is copied from: https://observablehq.com/@d3/force-directed-graph?collection=@d3/d3-force. Only the dblclick is added. It is working in version 5, but as a separate function.
How can I add dblclick in version 6.1 of D3.js the correct way?
回答1:
First, there is no "dblclick"
typename for drag.on
, which is not the same of selection.on
. Hence your error:
Error: unknown type: dblclick
The only valid typenames are: "start"
, "drag"
and "end"
. That said, your code should not work, be it v5 or v6.
The rest of this answer deals with another major problem with D3 v6:
As specified in the API, selection.on()
in D3 version 6 passes the event as the first argument:
When a specified event is dispatched on a selected element, the specified listener will be evaluated for the element, being passed the current event (event) and the current datum (d), with this as the current DOM element (event.currentTarget)
Therefore, your function should be:
function dblclick(_, d) {
d.fx = null;
d.fy = null;
}
Here, the _
is just a JavaScript convention telling us that the first parameter (the event) is never used.
来源:https://stackoverflow.com/questions/63670618/double-click-event-not-working-on-d3-version-6-1