[英]Access class functions from d3 event handler
I'm trying to use es6 classes in a d3 app. 我正在尝试在d3应用程序中使用es6类。 I have an event handler bound to the "drag" event, but I cannot access the class from within the event handler.
我有一个绑定到“拖动”事件的事件处理程序,但是我无法从事件处理程序中访问该类。
this
is my class when I manually call the handler, but when the event is triggered, this
is the DOM element. 手动调用处理程序时,
this
是我的类,但是触发事件时, this
是DOM元素。
Code: 码:
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})`);
}
}
You loose the binding to this when you pass a function that way. 以这种方式传递函数时,您将失去对此的绑定。 It passes a reference to the function, which D3 calls, so the calling context changes.
它传递对D3调用的函数的引用,因此调用上下文会更改。 You can keep
this
by explicitly binding it. 你可以把
this
通过明确绑定它。
call(d3.drag(this).on('drag', this.onDrag.bind(this))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.