我正在使用 Chart.js
和 plugin拖动数据点。图表需要传递一个 options
对象来对其进行自定义,并在存在 dragEnd
事件时触发与选项一起传递的回调。我想在触发事件时修改 options
对象的数据集。如何使事件超出其范围,以便我可以进行操作。
@Component({
selector: 'app-line-chart',
templateUrl: './line-chart.component.html',
styleUrls: ['./line-chart.component.css']
})
export class LineChartComponent implements OnInit {
@ViewChild('myChart') myChart: BaseChartDirective;
public chartInstance: Chart;
public context: CanvasRenderingContext2D;
public options: any = {
type: 'line',
data: {
labels: [2010, 2011, 2012, 2013, 2014],
datasets: [
{
label: 'Marks',
data: [120, 90, 30, 50, 20, 30],
borderWidth: 3,
borderColor: "#00a2e8",
fill: false
}
]
},
options: {
dragDataRound: 0,
dragData: true,
scales: {
yAxes: [{
ticks: {
reverse: false
}
}]
},
onDragEnd: function (e, datasetIndex, index, value) {
console.log('Event Triggered'); // This works fine.
//Here I want to trigger a function outside its scope.
this.dragEndEvent(e, datasetIndex, index, value);
}
}
};
dragEndEvent(e, datasetIndex, index, value) {
//Do some manipulations on the myChartOptions object.
// When this event is triggered, I cannot acccess options object.
// console.log(this.options);
//Error: Cannot read property 'options' of undefined
}
constructor() { }
ngOnInit() {
}
ngAfterViewInit(): void {
this.chartInstance = new Chart(this.myChart.ctx, this.options);
}
}
最佳答案
您必须使用箭头函数来引用此上下文
试试这个:
public myChartOptions = {
type: 'line',
data: {...},
options: {
dragData: true,
dragX: false,
dragDataRound: 0,
dragOptions: {
magnet: {
to: Math.round
}
},
onDragEnd: (e, datasetIndex, index, value) => {
console.log('Event Triggered'); // This works fine.
//Here I want to trigger a function outside its scope.
this.dragEndEvent(e, datasetIndex, index, value);
}
}
}
dragEndEvent(e, datasetIndex, index, value) {
//Do some manipulations on the myChartOptions object.
// This is not getting triggered.
}
关于javascript - 如何获取对象范围之外的回调事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60286745/