Home > Net >  this.textSize is not a function
this.textSize is not a function

Time:06-02

I have this error :

Uncaught (in promise) TypeError: this.textSize is not a function

for this.textSize if I just put textSize it tells me that it is not defined.

while they are in the same file one below the other

textSize(text, classname="textDefault") {
        /* Get the size of the given text rendered in pixels.
        text : string
        output : dict
        */
        if (!d3) return;
        let container = d3.select("body")
            .append("svg");
        container.append("text")
            .attr("class", classname)
            .attr("x", -99999)
            .attr("y", -99999)
            .text(text);
        let size = container.node().getBBox();
        container.remove();
        return { "width": size.width, "height": size.height };
    },
    getYTickNumberWidth(dataValues, tickLabelFormat) {
        /* Get width for y tick number labels.
        dataValues : list/float
        tickLabelFormat : function
        output : float
        */

        return d3.max(dataValues.map(
            function(d) {
                console.log(this.textSize())
                let size = this.textSize(tickLabelFormat(d));
                return size.width;
            }
        ));
    },

CodePudding user response:

I think the problem is that you are using a function instead of an arrow function. try this:

    getYTickNumberWidth(dataValues, tickLabelFormat) {
    /* Get width for y tick number labels.
    dataValues : list/float
    tickLabelFormat : function
    output : float
    */

    return d3.max(dataValues.map(
        (d) => {
            console.log(this.textSize())
            let size = this.textSize(tickLabelFormat(d));
            return size.width;
        }
    ));
}

CodePudding user response:

Here issue is with the scope of this. As you are using regular function inside map which contains it's own this and trying to access textSize in it's own scope.

Hence, You have to use arrow function in which the value of this remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.

Demo :

new Vue({
  el: '#app',
  data: {
    items: []
  },
  methods: {
    textSize(item) {
        this.items.push(item)
    },
    getYTickNumberWidth() {
      this.items = [];
        /* [1, 2, 3].map(function(item) {   // ❌
                this.textSize(item);
              }); */
      
      [1, 2, 3].map((item) => {    // ✅
        this.textSize(item);
      });
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="getYTickNumberWidth">
  Get Items
  </button>
  <pre>{{ items }}</pre>
</div>

  • Related