[英]Access class functions from d3 event handler
我正在尝试在d3应用程序中使用es6类。 我有一个绑定到“拖动”事件的事件处理程序,但是我无法从事件处理程序中访问该类。 手动调用处理程序时, 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})`);
}
}
以这种方式传递函数时,您将失去对此的绑定。 它传递对D3调用的函数的引用,因此调用上下文会更改。 你可以把this
通过明确绑定它。
call(d3.drag(this).on('drag', this.onDrag.bind(this))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.