D3.drag():初始化"start"然后用它来拖拽和“;以何种;

d3.drag(): initialize a variable on "start" and use it on "drag" and "end"

本文关键字:quot 何种 start drag 初始化 然后 D3      更新时间:2023-09-26

我有一个类似下面的代码:

    var dragme = d3.drag()
        .on("start", function (d) {
           var variable1 =   // complex calucaltion result;
        })
        .on("drag", function (d) {
            //do something with variable1 without repeating the complex calculation 
        })
        .on("end", function (d) {
            //access variable1 again without repeat calculation
        });

如果不将variable1扩展到drag()的上下文中,如何实现这一点?

UPDATE:函数调用如下:

d3.select("#container").call(dragme); //#container is a svg group

你可以这样做:

var dragme = d3.drag()
        .on("start", function (d) {
           var variable1 = d3.select(this).attr("x");
           //do some heavy calculation and store in variable
           var calculation = 12354;
           //store it in the data model.
           d.calculation = calculation; 
        })
        .on("drag", function (d) {
          //do something with d.calculation
        })
        .on("end", function (d) {
          //do something with d.calculation    
        });

由于你没有数据,这是不太好的方法:

var dragme = d3.drag()
        .on("start", function (d) {
           var variable1 = d3.select(this).attr("x");
           //do some heavy calculation and store in variable
           var calculation = 12354;
           //store it in the data model.
           d3.select(this)[0][0].my_data = 1234;
        })
        .on("drag", function (d) {
          var calculation = d3.select(this)[0][0].my_data;
          //do something with calculation
        })
        .on("end", function (d) {
          var calculation = d3.select(this)[0][0].my_data;
          //do something with calculation    
        });