gpt4 book ai didi

javascript - 将 JavaSscript 构造函数属性传递给 mouseover 函数并仍然使用 d3.select(this)

转载 作者:行者123 更新时间:2023-12-03 00:38:49 24 4
gpt4 key购买 nike

我正在尝试在 this.HandleMouseOver 中使用 d3.select(this)this.data_。我尝试了各种方法来解决该问题,例如将 .on('mouseover', this.handleMouseOver); 转换为 .on('mouseover', function(){ this.handleMouseOver( d3.select(this), this.data_); });//>> 错误:this.handleMouseOver 不是函数 - 但到目前为止还没有运气(是的,我在 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
}

最佳答案

您可以尝试选择全局事件d3.event.target并将范围绑定(bind)到事件函数

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
}
}

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

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
}
}

关于javascript - 将 JavaSscript 构造函数属性传递给 mouseover 函数并仍然使用 d3.select(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53547436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com