Search code examples
javascriptvue.jschartist.js

Get variable within function and assign it to another variable out of its scope


I am using Chartist and VueJS and I am trying to access data within my chart. When I click my chart, I should be able to get the information about the index of my click. I get this data, but I am having trouble passing that data to Vue itself.

Here is my current code:

  data() {
    return {
      monthIndex: 0,
      chartData: {
        labels: [],
        series: [[], []]
      },

      /* other chart options that I omitted */

      chartEventHandlers: [
        {
          event: "draw",
          fn(data) {
            if (data.type === "bar") {
              data.element.animate({
                y2: {
                  begin: data.index * 40,
                  dur: "0.3s",
                  from: data.y1,
                  to: data.y2,
                  easing: "easeOutQuad"
                },
                opacity: {
                  begin: data.index * 40,
                  dur: "0.3",
                  from: 0,
                  to: 1,
                  easing: "easeOutQuad"
                }
              });

              data.element._node.onclick = evt => {
                console.log(data.axisX.ticks[data.index]);
               // How do I assign this to monthIndex??

              };
              //
            }
          }
        }
      ]
    };
  }

As you can see here:

data.element._node.onclick = evt => {
                console.log(data.axisX.ticks[data.index]);
              };

I can get it to display the correct value in the console, I just am trying to figure out a way to make

monthIndex = data.axisX.ticks[data.index]

However, monthIndex does not exist in the scope of the function, so I can't simply assign it to that variable. How do I go about doing this? I am trying to get monthIndex to show up on the html View so that it changes everytime I click on another part of the chart.


Solution

  • What @Chris Li is saying is that you can bind the Vue scope to a function by doing this:

    function(data) {
    
    }.bind(this)
    

    Which allows you to access the Vue scope, or this inside of the function so to be able to assign the index value to the appropriate variable.