我正在使用d3.js v4.4和Angular 2。

我有一些可拖动的气泡,拖动效果很好。如果访问拖放到x和y,现在我需要做的是,使用这些值与位于我的组件上的数据集一起计算一个值。我遇到的问题是我的拖动结束函数,这是指被拖动的对象,我无权访问实际的父范围。

这就是我添加气泡的方式。

showPeopleBubble() {
        let self = this;
        console.log('run')
        this.bubblePeople = this.canvas.selectAll('.bubblePeople')
            .data(this.nodes)
            .enter().append('g')
            .attr('class','.bubblePeople').attr('id',function(d){return 'i'+d.index})
            .attr('transform',"translate(100,100)")
            .call(D3['drag']().on("start", self.dragstarted)
                .on("drag", self.dragged)
                .on("end", self.dragended));

            this.bubblePeople.append("title").text(function(d){return d.name + ' ('+d.index+')'})

            this.bubblePeople.append('circle')
                .attr('r',30)
                .attr('fill','blue')
                .attr('fill-opacity',.3)
                .attr("text-anchor","middle")

            this.bubblePeople.append('text').text(function(d){return d.name.substring(0,30/3)});

    }

dragended(d) {
   // this in here is the bubble that i'm dragging
//i need to access the parent level.


}

最佳答案

您可以像这样手动使用回调:

showPeopleBubble() {
        let self = this;
        console.log('run')
        this.bubblePeople = this.canvas.selectAll('.bubblePeople')
            .data(this.nodes)
            .enter().append('g')
            .attr('class','.bubblePeople').attr('id',function(d){return 'i'+d.index})
            .attr('transform',"translate(100,100)")
            .call(D3['drag']().on("start", self.dragstarted)
                .on("drag", self.dragged)
                .on("end", function(d){
                    return self.dragended(d, this, self);
                 }));

            this.bubblePeople.append("title").text(function(d){return d.name + ' ('+d.index+')'})

            this.bubblePeople.append('circle')
                .attr('r',30)
                .attr('fill','blue')
                .attr('fill-opacity',.3)
                .attr("text-anchor","middle")

            this.bubblePeople.append('text').text(function(d){return d.name.substring(0,30/3)});

    }

dragended(d, innerThis, globalThis) {
   // this in here is the bubble that i'm dragging
//i need to access the parent level.
  //  globalThis.someFunction();  <-- will call the global someFunction() method

}

someFunction(){}


我还放置了函数this,这样您就不会在全局范围内的dragended(d)函数中丢失它。

10-05 20:34
查看更多