首页 > 解决方案 > 如何获取对象范围外的回调事件?

问题描述

我正在使用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);
  }
}

标签: javascriptangulartypescript

解决方案


您必须使用箭头函数来引用此上下文

试试这个:

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

推荐阅读