SachDan SachDan - 2 months ago 6
Javascript Question

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

I have a code similar to the one below:

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


How can this be achieved without extending
variable1
out of the drag()'s context?

UPDATE: The function call is as follows:

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

Answer

You can do like this:

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

Since you don't have a data this is the not so good way:

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