首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Chart.js:在onRefresh()方法外部调用方法

Chart.js:在onRefresh()方法外部调用方法
EN

Stack Overflow用户
提问于 2020-02-02 08:50:38
回答 2查看 96关注 0票数 0

我已经附上了代码片段。我在HomeComponent类的rand()中有一个方法,我想为y轴调用它,但从目前的情况来看,这是不可能的,因为无论何时onRefresh() get调用this.rand()都是不可访问的,这是预期的。因为onRefresh()是从核心库core.js调用的。所以请帮我把这件事做完

代码语言:javascript
复制
export class HomeComponent implements OnInit, OnDestroy {
....
..
options: any = {
    scales: {
      xAxes: [
        {
          type: 'realtime',

          realtime: {
            onRefresh(chart: any) {


              chart.data.datasets.forEach(function(dataset: any) {
                dataset.data.push({
                  x: Date.now(),

                  **y: this.rand()**
                });
              });
              chart.config.options.scales.yAxes[0].ticks.min = chart.helpers.niceNum(20);
              chart.config.options.scales.yAxes[0].ticks.max = chart.helpers.niceNum(180);
            },

            delay: 2000
          }
        }
      ]
    },
    annotation: {
      annotations: [
        {
          type: 'line',
          mode: 'horizontal',
          scaleID: 'y-axis-0',
          value: '120',
          borderColor: 'tomato',
          borderWidth: 2
        },
        {
          type: 'line',
          mode: 'horizontal',
          scaleID: 'y-axis-0',
          value: '70',
          borderColor: 'blue',
          borderWidth: 2
        }
      ]
      //drawTime: "afterDraw" // (default)
    }
  };
  ....
  ....
  
  rand(): Number {
    return Math.floor(Math.random() * (200 - 100 + 1)) + 100;
  }
  }

提前感谢:)

EN

回答 2

Stack Overflow用户

发布于 2020-02-02 09:12:57

考虑到您的rand实现,简单地对X轴数据执行这些操作还不够吗?

i.e

代码语言:javascript
复制
                dataset.data.push({
                  x: Date.now(),
                  y: Math.floor(Math.random() * (200 - 100 + 1)) + 100;
                });
票数 0
EN

Stack Overflow用户

发布于 2020-02-02 20:13:06

这个问题可以通过在类HomeComponent外部声明全局变量,并在HomeComponent的构造函数主体中将'this‘赋给已声明的变量来解决。之后,我们可以轻松地访问方法和实例变量。

谢谢:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60022404

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档