What is the best way to reference class variables and methods within a callback function in Typescript?

While working on my Angular project with the Highcharts API, I encountered a situation where I needed to pass a state code to a class level method after drilling down to a specific map location.

Below is the snippet of my current code:

ngOnInit() {

this.chartOptions = {
  chart: {
    height: (8 / 16) * 100 + '%',
    events: {
      drilldown(e) {
        // ERROR Error: this.getVendorProductStatsByStateCode is not a function
        this.getVendorProductStatsByStateCode(e.point.drilldown);
        const chart = this as any;

        const mapKey = 'countries/ca/' + e.point.drilldown + '-all';
        const mapData = require(`@highcharts/map-collection/countries/ca/ca-on-all.geo.json`);
        const provinceData = Highcharts.geojson(mapData);
        provinceData.forEach((el: any, i) => {
          el.value = i;
        });

        chart.addSeriesAsDrilldown(e.point, {
          name: e.point.name,
          data: provinceData,

          dataLabels: {
            enabled: true
          }
        });

        chart.setTitle(null, { text: e.point.name });
      },
      drillup() {
        const chart = this as any;
      }
    }
  },
  title: {
    text: ''
  },
  colorAxis: {
    min: 0,
    minColor: '#E6E7E8',
    maxColor: '#417BCC'
  },

  mapNavigation: {
    enabled: true,
    buttonOptions: {
      verticalAlign: 'bottom'
    }
  },
  plotOptions: {
    map: {
      states: {
        hover: {
          color: '#F8BA03'
        }
      }
    }
  },
  series: [
    {
      name: 'Canada',
      data: caMap
    }
  ],
  drilldown: {}
};
}

getVendorProductStatsByStateCode(mapstateCode) {
    console.log(mapstateCode);
}

Here is the live example on StackBlitz

When invoking the drilldown function, I aim to access

this.getVendorProductStatsByStateCode
, which resides in one of my class component methods. What would be the correct approach to achieve this?

Answer №1

If you want to avoid using "this" as a reference to your component, you can store it in a variable and then use that variable instead. Here's an example:

  caMap.forEach((el: any, i) => {
      el.value = i;
      el.drilldown = el.properties['hc-key'];
    });
    var myComp = this;
    this.chartOptions = {
      chart: {
        height: (8 / 16) * 100 + '%',
        events: {
          drilldown(e) {
            // ERROR Error: this.getVendorProductStatsByStateCode is not a function
            myComp.getVendorProductStatsByStateCode(e.point.drilldown);
            const chart = this as any;

            const mapKey = 'countries/ca/' + e.point.drilldown + '-all';
            //Stackbliz wont load data if you pass mapkey as variable. So I use a hard code one in this example.
            // const mapData = require(`@highcharts/map-collection/${mapKey}.geo.json`);
            const mapData = require(`@highcharts/map-collection/countries/ca/ca-on-all.geo.json`);
            const provinceData = Highcharts.geojson(mapData);
            // Set a random value on map
            provinceData.forEach((el: any, i) => {
              el.value = i;
            });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Disable the mousedown event in JavaScript/jQuery

During a drag and drop operation, I have set certain limits on the screen. When the draggable object passes these limits, I want it to return to its original position. The issue I am facing is that if the onmousedown event is active, the object does not r ...

Clear out a collection in backbone.js

I am looking to clear out a collection by removing each item in sequence. this.nodes.each(function(node){ this.nodes.remove(node); }, this); The current method is ineffective as the collection length changes with each removal. Utilizing a temporary arr ...

Error encountered during Angular ng build -prod: The provided parameters do not align with any applicable call target signatures

Every time I try running ng build --target=production, an error pops up like this: ERROR in C:/Repo/NewCo/src/$$_gendir/app/fu/bar/fubar.component.ngfactory.ts (4011,35): Supplied parameters do not match any signature of call target. This error m ...

I keep encountering an Uncaught TypeError when trying to read the property 'options' of null, despite having the element ID properly defined

I am a newcomer to the world of Javascript and HTML. Despite having the element defined in HTML, I am encountering an exception. Could someone please offer assistance? My goal is to create a shape (initially a circle) based on user input such as shape type ...

Unable to perform updates for personalized fonts

I've been trying to incorporate custom fonts into my website, but I seem to be facing difficulties in actually implementing them. Could someone please let me know if I am doing it correctly? .pattern{ background:rgba(0,0,0,.5) url(../images/pattern ...

How do I utilize Ajax to compare the value selected from a drop down menu in a form with entries in my database, and retrieve the corresponding record/row to automatically fill in a form?

I have a drop-down menu where users can select an option. I need to match the selected value with the corresponding record in my database under the "invoiceid" column, and then populate a form with the associated data when a prefill button is clicked. Belo ...

Emphasize the center row within a moving table

I am interested in developing a scrolling table where only 10 rows are visible at any given time, with the middle row set to stand out even during scrolling. The concept is that as the user scrolls down, the highlighted row changes progressively as they c ...

Launch a YouTube video within a sleek and stylish Bootstrap modal popup

I am currently extracting video data from my SQL table. The fields in the table are as follows: - sidebar_video_id (auto increment) - sidebar_video_nev - sidebar_video_link (full URL) - sidebar_video_v_id (video ID at the end of the URL) What I'm tr ...

A sleek CSS text link for a stylish video carousel

I am attempting to create a CSS-only text link to video slider within our Umbraco CMS. Due to the limitations of TinyMCE WYSIWYG, I am restricted in the amount of code I can use as it will strip out most of it. So far, I have developed a basic CSS slider ...

What could be causing transition to not be recognized as an element in HTML?

<template> <header> <nav class="container"> <div class="branding"> <router-link class="header" :to="{name : 'Home'}">>FireBlogs</router-link> </div& ...

Can you explain the concept of an anonymous block in JavaScript ES6 to me?

Recently, I came across an article on pragmatists which discussed some interesting ES6 features. However, one concept that caught my attention was the use of an anonymous block within a function. function f() { var x = 1 let y = 2 const z = 3 { ...

Integrating an API with a Discord bot using an embedded link in Discord.js

I am currently in the process of creating a bot that can generate and embed links to display manga titles, tags, and other information based on user-input digits. I have been exploring an API called this and I am eager to learn the most effective method ...

How can I achieve a fade-in effect whenever the flag image is clicked?

A unique "international" quotes script has been created, showcasing Dutch, English, German, and French quotes. The script displays different quotes every day, with a draft-result visible in the upper right corner of this page ... The code used for this sc ...

Struggling to extract the hours and minutes from a date in IONIC: encountering an error stating that getHours is not a recognized

I encountered an issue while trying to extract the hours and minutes from a date in Ionic. Below is the code snippet from my .html file : <ion-datetime displayFormat="HH:mm" [(ngModel)]='timeEntered1' picker-format="h:mm"></ion-date ...

Mongoose: execute population step after making the query

What is the proper way to populate the query result in Mongoose after executing a query similar to this: users .find({name:"doejohn"}) .skip(3) .limit(9) .exec((err,user) => { user // result ...

What is the process for making local dynamoDB queries with dynamoose?

In order to avoid constantly connecting to Amazon Web Services as a developer, I decided to install DynamoDB on my local computer following the guidelines provided in the AWS Docs. My backend is built using node.js. For modeling Amazon's DynamoDB in ...

How selection.join behaves when every node contains child elements

I have been following the amazing tutorial on to learn more about the join paradigm. Everything was working fine until I tried to make each node more complex by adding a group with text inside. The main group gets updated, but the child one does not. Sn ...

It is not possible to use Date.now within passport.js

When creating a user via Facebook on my Node.js website using passport, I want to assign the register date. In my Mongoose Schema, I can use the following for the local provider: regisDate: { type: Date, default: Date.now }, However, when it co ...

The first three AJAX requests are successful, but the fourth one fails to reach the PHP script

I am currently working on cascaded selects (a total of 4) that retrieve data from a database. To populate them, I use SQL queries based on the selection made in the previous select element. To establish communication between the select element and the subs ...

Searching for nested divs with the same class name in jQuery can be achieved by using the

Need assistance in locating all divs with a specific class name. Some divs may have nested divs with the parent div's class name. Take this scenario for example: <div class="myForm"> <div class ="myDiv"> <div class ="myDiv"> ...