如何在HighCharts中的click函数中访问外部范围变量 [英] How to access outer scope variables within a click function in HighCharts

查看:241
本文介绍了如何在HighCharts中的click函数中访问外部范围变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Angular 7和HighCharts一起使用.我正在向高图表点击事件传递一个函数,但是我还需要从组件访问一些变量.

I'm using Angular 7 along with HighCharts. I'm passing a function to my high charts click event, but I also need to access some variable from the component.

这是我的活动代码:

events: {
        click: function (e: any) {
          console.log(this.xAxis[0].min)
          console.log(this.componentVariable)
        }
      } 

我可以访问xAxis的值,但不能访问变量componentVariable,因为它在上下文中不存在.我也不能bind this使用该函数,因为那样我将无法访问xAxis.

I can access the value of xAxis but not the variable componentVariable because it doesn't exist in the context. I cannot bind this to the function either, because then I won't have access to xAxis.

如何访问click回调函数中的两个变量?

How can I access both variables inside the callback click function?

此处是我遇到的问题的一个简单示例.

Here is a simple example of my problem.

推荐答案

我对Angular不太了解,但是为了在回调中访问此属性,您必须在构造函数中创建一个辅助常量,将this绑定到它.这是来自stackblitz的代码的修改后的版本:

I don't know much about Angular, but in order to access this property inside the callback, you'd have to create a helper constant inside the constructor and bind this to it. Here's a modified version of your code from stackblitz:

import { Component } from '@angular/core';

@Component({
    selector: 'simple-chart-example',
    template: `
        <chart [options]="options"></chart>
    `
})

export class AppComponent {
    componentVariable: Number; //Declaring your property
    constructor() {
        const that = this; //Creating the helper constant that can be used in callbacks to refer to the AppComponent's context
        this.componentVariable = 15; //Assigning a value to your property
        this.options = {
            title: {
                text: 'simple chart'
            },
            series: [{
                data: [29.9, 71.5, 106.4, 129.2],
            }],
            chart: {
                events: {
                    click: function(e: any) {
                        console.log(this.xAxis[0].min);
                        console.log(that.componentVariable); //Using the helper constant to access your declared property
                    }
                }
            },
        };
    }
    options: Object;
}

这篇关于如何在HighCharts中的click函数中访问外部范围变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆