我正在使用d3.js v4.4和Angular 2。
我有一些气泡,拖拽和拖拽工作正常。如果访问drag-to 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.
}
答案 0 :(得分:1)
您可以手动使用这样的回调:
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)
函数中丢失它。
答案 1 :(得分:0)
最后使用.bind,我可以绑定它或我需要的数据。
.call(D3['drag']().on("start", self.dragstarted)
.on("drag", self.dragged)
.on("end", self.dragended.bind(this)));