0

I have the following onClick function inside my ChartJS instance. It works perfectly to access component variables.

onClick: () => {
    console.log(this.test);
  },

Now I need to get some informations about the chart.

For example:

Using this function bellow I can access event of click and array but I can't access component variable like in the first arrow function

chartClickEvent(event, array) {
    const ENTRADA = 0, SAIDA = 1;
    if (array[0]) {
      let columnIndex = array[0]._index;
      if (columnIndex == ENTRADA) {
        console.log(this.test);
      }
    }
  }

It's shows undefined when I try to print component variable

onClick: chartClickEvent,

How to access both? Data about chart and component variable

3
  • 2
    onClick: (event, array) => this.chartClickEvent(event, array) Commented Jun 28, 2019 at 12:38
  • @David it's works like a charm. Could you create a answer for that? Commented Jun 28, 2019 at 12:42
  • 1
    It's alright, no worries =) Commented Jun 28, 2019 at 13:21

1 Answer 1

1

Use the Function.prototype.bind function:

onClick: chartClickEvent.bind(this)

What happens here is when chartClickEvent is being executed the scope is different and so the this is not what you expected.

The bind function returns a new function that is bound to the this you defined.

You can, of course, use an arrow function there as well:

onClick: (event, array) => chartClickEvent(event, array)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you man. David answered first in the comments area but If he does not create a answer I going to accept yours

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.