[英]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.