javascript - 如何获取对象范围之外的回调事件?

标签 javascript angular typescript

我正在使用 Chart.jsplugin拖动数据点。图表需要传递一个 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/

相关文章:

javascript - Chrome 中凌乱的鼠标事件

javascript - Angular2 应用程序无法在 Firebug 启动的情况下运行

angular - 无法正确使用继承 Ionic 2

javascript - 主干 - View 未渲染

javascript - 如何让第一个元素显示在 dom-repeat 中?

javascript - HTML 文件未在 Django 中正确加载

仅带有 <template> 的 Angular2 ngSwitch

angular - 在 router-outlet 注入(inject)的延迟加载模块中使用面包屑组件

typescript - 将函数参数类型限制为特定类型接口(interface)的键

typescript 提示 : Cannot find name 'Notification'