我正在尝试在 d3 应用程序中使用 es6 类。我有一个绑定(bind)到“拖动”事件的事件处理程序,但我无法从事件处理程序中访问该类。当我手动调用处理程序时,this
是我的类,但是当触发事件时,this
是 DOM 元素。
代码:
class Point {
constructor(croot, cx, cy, ccolor) {
this.x = cx;
this.y = cy;
this.size = 5;
this.draggable = true;
this.root = croot;
this.color = ccolor;
this.circle = this.root.append('circle')
.attr('class', "draggable")
.attr('r', this.size)
.attr('fill', "white")
.attr('stroke', this.color)
.attr('stroke-width', 2)
.call(d3.drag(this).on('drag', this.onDrag));
this.circle.attr('transform',
`translate(${(this.x + 0.5) * scale} ${(this.y + 0.5) * scale})`);
}
onDrag() {
console.log(this);
this.x = (d3.event.x / scale);
this.y = (d3.event.y / scale);
this.circle.attr('transform',
`translate(${(this.x + 0.5) * scale} ${(this.y + 0.5) * scale})`);
}
}
最佳答案
当您以这种方式传递函数时,您就失去了与 this 的绑定(bind)。它传递对 D3 调用的函数的引用,因此调用上下文发生变化。您可以通过显式绑定(bind)来保留 this
。
call(d3.drag(this).on('drag', this.onDrag.bind(this))
关于javascript - 从 d3 事件处理程序访问类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51224676/