Search code examples
javascriptrecursionvue.jsvuejs2vue-chartjs

How to stop infinite recursion in callback


I've been trying to understand why and how to fix this infinite recursion happening in the legendCallback Vue's Vue-charts to no avail. Help is much appreciated.

In my Vue component, options is defined in methods as:

  options() {
                var self = this;
                 return {
                    legend: {
                        display: false,
                        position: 'top',
                    },
                    legendCallback: chart=> {
                        return this.generateLegendData(chart)
                    },
                    tooltips: {
                        mode: 'single',
                        callbacks: {
                            label: function (tooltipItems) {
                                return "text"
                            }
                        },
                    }
                }
            },

And my generateLegendData method looks like this:

        generateLegendData(chart) {
          var labels = ["SolarCity", "Einstein", "SpaceX", "Mars", "Tesla"];
          var backgroundColor = [
            "rgba(242,58,48, 0.1)",
            "rgba(110,75,63,1)",
            "rgba(55,72,172,1)",
            "rgba(0,39,39,1)",
            "rgba(166,176,69,1)"
          ];

          var text = [];
          text.push('<ul class="' + chart.id + '-legend">');
          for (var i = 0; i < labels.length; i++) {
            text.push(
              '<li><span style="background-color:' + backgroundColor[i] + '">'
            );
            if (labels[i]) {
              text.push(labels[i]);
              console.log(labels[i]);
            }
            text.push("</span></li>");
          }
          text.push("</ul>");

          return text.join("");
        }

Without the for loop, i.e just returning the expected string it works fine.


Solution

  • Returning return text.join("") was not the problem.

    The solution is moving options property from a method to a computed property.