簡體   English   中英

從d3事件處理程序訪問類函數

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM