简体   繁体   中英

Access class functions from d3 event handler

I'm trying to use es6 classes in a d3 app. 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.

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. You can keep this by explicitly binding it.

call(d3.drag(this).on('drag', this.onDrag.bind(this))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM