Typescript/D3 v4 - Context of this in d3.drag().on(“end”, this.dragended)

后端 未结 3 694
后悔当初
后悔当初 2021-01-18 07:46

I am using the D3 library to move an item within a Venn-diagram. When I stop dragging I want to determine the position of the item in the diagram.

item.call(         


        
3条回答
  •  忘掉有多难
    2021-01-18 08:35

    If you need to keep the reference to the class instance and also the element instance referenced by d3 drag you can define your listener functions as:

    export class MyClass {
        @Input()
        radius: number = 45;
    
        constructor() {
            d3.drag()
              .on("start", this.dragStarted(this))
              .on("drag", this.dragged(this))
              .on("end", this.dragEnded(this));
        }
    
        private dragged(self) {
            return function(d) {
                // 'this' in this context will be the d3 element
    
                d3.select(this)
                  .attr("cx", d.x = self.radius * Math.cos(alpha))
                  .attr("cy", d.y = d3.event.y < 0 ? -self.radius * Math.sin(alpha) : self.radius * Math.sin(alpha));
            }
        }
    
        ...
    
    }
    

    Tested with d3.js v4

提交回复
热议问题