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

标签 javascript d3.js

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

    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()上下文之外的情况下实现这一点?

更新:函数调用如下:

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    
        });

关于javascript - d3.拖拽() : initialize a variable on "start" and use it on "drag" and "end",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39607965/

相关文章:

javascript - 从另一个函数读取值的正确方法是什么?

javascript - 那么区 block 不会在链式 promise 中被调用

javascript - initCustomEvent 方法的传递数据不再起作用

javascript - d3.js 中的缩放 donut 大小

javascript - 在 Javascript 集中查找最大值/最小值

javascript - 即使具有唯一的 id 值,d3 退出选择也会显示为空

javascript - 如何在 Node 中使用 x.509 证书验证 JWT token ?

Javascript 私有(private)实例变量?

javascript - 当某些节点被删除时更新 D3 树

javascript - 从 JSON 对象获取最大值 D3JS