ChartJS Angular |访问函数中的变量

bqjvbblv  于 2022-11-06  发布在  Chart.js
关注(0)|答案(2)|浏览(161)

我有一个图表JS插件,当用户在图表上移动时,它会返回一个事件。我想在onDrag事件发生时,将isOnDrag变量设置为true。

dragData: {
  dragX: true,
  onDragStart: function(e: Event) {
    console.log(e)
  },
  onDrag: function(e: Event, datasetIndex: any, index: any, value: { x: number; }) {
    this.isOnDrag = true; // I want to edit this global var
    value.x = new Date(value.x + 43200000).setHours(0, 0, 0, 0);
  },
  onDragEnd: function(e: Event, datasetIndex: any, index: any, value: { x: number; }) {
    this.isOnDrag = false; // I want to edit this global var
  },
},

在脚本的开头,我定义了如下变量:

isOnDrag: boolean = false;

下面的代码给出了这个错误:

TS2551: Property 'isOnDrag' does not exist on type '{ dragX: boolean; onDragStart: (e: Event) => void; onDrag: (e: Event, datasetIndex: any, index: any, value: { x: number; }) => void; onDragEnd: (e: Event, datasetIndex: any, index: any, value: { ...; }) => void; }'. Did you mean 'onDrag'?
rsaldnfx

rsaldnfx1#

将匿名函数更改为粗箭头语法

dragData: {
  dragX: true,
  onDragStart: (e: Event) => {
    console.log(e)
  },
  onDrag: (e: Event, datasetIndex: any, index: any, value: {
    x: number;
  }) =>  {
    this.isOnDrag = true; // I want to edit this global var
    value.x = new Date(value.x + 43200000).setHours(0, 0, 0, 0);
  },
  onDragEnd: (e: Event, datasetIndex: any, index: any, value: {
    x: number;
  }) => {
    this.isOnDrag = false; // I want to edit this global var
  },
},

.bind(this)

dragData: {
  dragX: true,
  onDragStart: function(e: Event) {
    console.log(e)
  }.bind(this),
  onDrag: function(e: Event, datasetIndex: any, index: any, value: {
    x: number;
  }) {
    this.isOnDrag = true; // I want to edit this global var
    value.x = new Date(value.x + 43200000).setHours(0, 0, 0, 0);
  }.bind(this),
  onDragEnd: function(e: Event, datasetIndex: any, index: any, value: {
    x: number;
  }) {
    this.isOnDrag = false; // I want to edit this global var
  }.bind(this),
},
qyzbxkaa

qyzbxkaa2#

修改函数定义。需要将函数定义为Arrow函数:

dragData: {
  dragX: true,
  onDragStart: (e: Event) => {
    console.log(e)
  },
  onDrag:(e: Event, datasetIndex: any, index: any, value: { x: number; }) => {
    this.isOnDrag = true; // I want to edit this global var
    value.x = new Date(value.x + 43200000).setHours(0, 0, 0, 0);
  },
  onDragEnd:(e: Event, datasetIndex: any, index: any, value: { x: number; }) => {
    this.isOnDrag = false; // I want to edit this global var
  },
},

根据我的理解,你的isOnDrag属性是在你的类中定义的。当你在Object中以常规的方式定义你的函数function name() {}时。this属性是定义函数的对象。

相关问题