我正在尝试在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
}
答案 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
}
}