javascript - 如何获取对象范围外的回调事件?
问题描述
我正在使用Chart.js
插件来拖动数据点。图表需要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.
}
推荐阅读
- algorithm - 这个for循环案例的时间复杂度是多少?
- swift - Xamarin 绑定 SWIFT 库:当构造函数具有参数时 SWIFT_UNAVAILABLE
- javascript - 如何检索和收集数组项目第一次出现的索引,同时考虑相同项目的连续顺序?
- java - Java删除文件中的行?
- php - 我没有在 UPI INTENT API Paytm 中获得深层链接
- javascript - 由于此错误消息未在组件中显示,存储更改不会立即对组件可见?
- node.js - 如何检查用户是否存在于nodejs中
- php - 如何在 Laravel 8 中使用基本身份验证编写 cURL 请求
- python - 训练 TensorFlow 模型时 GPU 利用率低
- javascript - 如何在 ajax Success 上向 Datatable 添加新行而不重新加载页面