Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript d3 passing arguments into a function that references d3.event.y

I want to edit the dragmove function to accept arguments. This is the original code:

var drag = d3.behavior.drag()
    .on("drag", dragmove)
    .on("dragend", function(d){console.log("dragend");    });

    focus.selectAll("circle")
               .data([coordinatesForecastCurrentMonth])
               .enter()
               .append("circle")
               .attr("cx", function(d) {
                    return x(d[0]);})
               .attr("cy", function(d) {
                    return y(d[1]);})
               .attr("r", function(d) {
                    return 5;})
               .attr("clip-path", "url(#clip)")
               .call(drag);
function dragmove(d) {
    d3.select(this)
      .attr("cy", d3.event.y);}

When I change it to the following:

.on("drag", dragmove(1,2))

function dragmove(arg1,arg2) {
    d3.select(this)
      .attr("cy", d3.event.y);

console.log(arg1);
console.log(arg2);}

I get this error: enter image description here

I don't understand why the event object cannot be found, can anyone help?

like image 886
user3156154 Avatar asked Oct 15 '25 08:10

user3156154


1 Answers

You are calling the function in your change instead of passing a reference to it. That is, you're calling it when the code is executed, not on drag. Hence, there's no d3.event. Make it a function reference like this.

.on("drag", function() { dragmove(1,2); });

The rest of the code can remain unchanged.

like image 176
Lars Kotthoff Avatar answered Oct 16 '25 21:10

Lars Kotthoff