Select element in drag event using arrow functions in v6
I'm using the drag event to move an element. In order to move the element I must select it first. I do this within arrow functions like so:
const drag = d3.drag()
.on('start', (e, d) => this.dragstarted(e, d))
.on('drag', (e, d) => this.dragged(e, d))
.on('end', (e, d) => this.dragended(e, d))
I wish to select the current element
dragged(event:any, d:any) {
console.log(d3.select(event.currentTarget))
}
This does not work. It seems to only work if I use a non arrow function:
const _this = this;
...
.on('drag', function (e, d) { _this.dragged(e, d, this) })
...
dragged(event:any, d:any, el:any) {
console.log(d3.select(el))
}
Version 5 passed the nodes and index of the element that could be used for selection:
dragged(d, i, nodes) {
d3.select(nodes[i])
}
Is there a way to select the svg element within the arrow function to get a handle on the item within the drag event in V6?
When calling the D3 drag handlers, this
is the same as event.sourceEvent.target
, so:
.on('drag', function(e, d) { onDrag(this, d); })
will work the same as:
.on('drag', (e, d) => onDrag(e.sourceEvent.target, d))
Please note that the code is valid for V6 / V7. For V5 or earlier, use d3.event.sourceEvent.target