简体   繁体   中英

How to programmatically trigger a D3 drag event?

So i have some data binded with drag event listeners :

myNodes.enter()
    .append("svg:g")
    .call(d3.behavior.drag()
        .on("drag", function() { 
            console.log(d3.event.dx, d3.event.dy);
        })
    );

Now I want to call this onDrag function on a certain node programmatically. I do know the same is possible with standard events by doing

aNode.on("click")() // works
aNode.on("drag")()  // doesn't work

Is there any way to do so ? Thanks.

Save the callback (the one you pass into the drag handler) in a variable and then call this variable in your other context.

var dragCallback = function(){
  console.log(d3.event.dx, d3.event.dy);
};
var dragBehavior = d3.behavior.drag()
                     .on("drag", dragCallback);
myNodes.enter()
  .append("g")
  .call(dragBehavior);
  //Call drag method programmatically
  dragCallback()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM