将 JavaSscript 构造函数 属性 传递到鼠标悬停函数中并仍然使用 d3.select(this)

Pass a JavaSscript constructor property into mouseover function & still use d3.select(this)

我正在尝试在 this.HandleMouseOver 中使用 d3.select(this)this.data_。我尝试了各种方法来解决这个问题,例如将 .on('mouseover', this.handleMouseOver); 转换为 .on('mouseover', function(){ this.handleMouseOver(d3.select(this), this.data_); }); // >> error: this.handleMouseOver is not a function - 但到目前为止运气不好(是的,我在 handleMouseOver(selection,data).

上添加了输入

关于如何在 handleMouseOver() 中访问 d3.select(this)this.data_ 有什么建议吗?

class Chart {
    constructor(opts){
        this.data_ = opts.data_;
        this.width_ = opts.width_;
        this.height_ = opts.height_;
        this.draw(); //create the chart
    }

    draw(){
        this.container = svgContainer.append('g')
            .attr('id', 'country-wrapper')
            .attr('width', this.width_)
            .attr('height', this.height_)
            .attr('transform', 'translate(0,0)')
            .on('mouseover', this.handleMouseOver);
            //.on('mouseout', this.handleMouseOut);

    }

    handleMouseOver(){
        var this_ = d3.select(this);
        console.log(this_, this.data_); // this.data_ >> it says it is undefined
}

您可以尝试 select 全局事件 d3.event.target 并将范围绑定到事件函数

class Chart {
    constructor(opts){
        this.data_ = opts.data_;
        this.width_ = opts.width_;
        this.height_ = opts.height_;
        this.draw(); //create the chart
    }

    draw(){
        this.container = svgContainer.append('g')
            .attr('id', 'country-wrapper')
            .attr('width', this.width_)
            .attr('height', this.height_)
            .attr('transform', 'translate(0,0)')
            .on('mouseover', this.handleMouseOver.bind(this));
            //.on('mouseout', this.handleMouseOut);

    }

    handleMouseOver() {
        var this_ = d3.select(d3.event.target);
        console.log(this_, this.data_); // this.data_ >> it says it is undefined
   }
}

或者如果您使用现代箭头函数,它会自动绑定您的上下文

class Chart {
        constructor(opts){
            this.data_ = opts.data_;
            this.width_ = opts.width_;
            this.height_ = opts.height_;
            this.draw(); //create the chart
        }

        draw(){
            this.container = svgContainer.append('g')
                .attr('id', 'country-wrapper')
                .attr('width', this.width_)
                .attr('height', this.height_)
                .attr('transform', 'translate(0,0)')
                .on('mouseover', this.handleMouseOver);
                //.on('mouseout', this.handleMouseOut);

        }

        handleMouseOver = () => {
            var this_ = d3.select(d3.event.target);
            console.log(this_, this.data_); // this.data_ >> it says it is undefined
       }
    }