将JavaSscript构造函数属性传递到mouseover函数中,并仍使用d3.select(this)

时间:2018-11-29 20:55:45

标签: javascript class d3.js this onmouseover

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

关于如何访问d3.select(this)中的this.data_handleMouseOver()的任何建议?

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
}

1 个答案:

答案 0 :(得分:1)

您可以尝试选择全局事件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
       }
    }