Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
965 views
in Technique[技术] by (71.8m points)

javascript - Double click event not working on D3 version 6.1

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...