The process of invoking a function within another function in TypeScript Angular

Just starting out with Angular 2, I've written the following code in my Angular project:

export class TestClass {

    constructor() {
        this.initMap();
    }

    initMap() {
        this.marker.addListener('dragend', this.onMarkerDrop);
    }

    onMarkerDrop(event) {
        this.functionTwo(); // I keep getting an error that says 'this.functionTwo' is not a function
    }

    functionTwo() {

    }
}

Note: Before reaching out for help, I did some research on Stack Overflow and found these relevant links:

'this.function' is not a function - OO JS

this.function is not a function :typescript

Angular - this.function is not a function

Based on what I read, it seems like using arrow functions to call other member functions might be the solution. However, I'm unsure of how to implement their suggestions in my own code. Perhaps I misunderstood something.

I'm seeking guidance on how to properly call `this.functionTwo()` using an arrow function from `functionOne()`. Your assistance would be greatly appreciated.

Thank you for your support.

Answer №1

When updating your code, remember to use it like this:

this.marker.addListener('dragend', this.onMarkerDrop.bind(this));
// OR
this.marker.addListener('dragend', ($event) => this.onMarkerDrop($event));

Your code is expected to work perfectly:

functionOne() {
    this.functionTwo(); // Error occurs - this.functionTwo is not a function
}

functionTwo() {
    alert('function2');
}

Please refer to the following code for further clarification

functionOne() {
    // Error will be thrown - this.functionTwo is not a function
    setTimeout(function(){ // normal function
        this.functionTwo();  
    })

    // No error will occur
    setTimeout(() => { // fat arrow
        this.functionTwo(); // Error occurs - this.functionTwo is not a function        
    })
}

functionTwo() {
    alert('function2');
}

Why using a fat arrow works:

'this' is captured from its lexical scope. Hence, no need for bind() or that = this.

With Normal functions, you are required to use bind() or that = this

Answer №2

When passing your function onMarkerDrop as a callback, be aware that the context can change and this may have a different value. To maintain the right context, consider using arrow functions or binding.

this.marker.addListener('dragend', this.onMarkerDrop.bind(this));

Alternatively,

this.marker.addListener('dragend', ($event) => this.onMarkerDrop($event));

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

Creating a modal window when a link is clicked in an MVC application

I am looking to open a Crystal Report in a pop-up window when a menu item is clicked. <%= Html.ActionLink("Display Name", "Action","Controller", new { target="blank"})%> The code above successfully opens the report, but it currently opens in a new ...

jsonwebtoken does not fetch a token

I've been working on a user registration system using nodejs and sequelize. So far, I've successfully implemented the login and register functionalities. However, I am encountering an issue with getting the token after a successful login. Despit ...

Exploring the utilization of functions beyond module exports

Striving to clearly communicate my intentions, please feel free to ask if anything is unclear. Within a file named www, I am configuring my socket as follows: var server = http.createServer(app); var io = require('socket.io')(server); require(& ...

What is the best approach to simultaneously update an array using multiple threads in a Node.js environment?

Hey there, I'm trying to figure out how to make changes to the same array using 2 worker threads in Node.js. Can anyone help me with this? My issue is that when I add a value in worker thread 1 and then try to access it in worker thread 2, the second ...

Performing Vue CLI Global Upgrade

Struggling to create a new Vue.js project using the Vue CLI service, I encountered an error. With @vue/cli-service 3.0.0-beta.7 installed (confirmed by running vue -V), attempting to start a new project triggered the following error: ...

Executing Selenium WebDriver to interact with a hidden element

Hello, I am interested in learning how to interact with hidden elements and disable them using Selenium WebDriver. I've managed to achieve this with Selenium 1 by using the following code: selenium.click(id="idOfHiddenField"); Unfortunately, this a ...

The npm package installation process encountered difficulties in accessing the Chart.Js library

Currently, I am in the process of developing a web application that tracks and logs hours spent on various skills or activities. The data is then presented to the user through a bar graph created using Chart.js. Initially, I was able to display a mock grap ...

Has anyone figured out the issue with Uplodify? It suddenly ceased to function

For some time now, I've been using uplodify without any issues. Unfortunately, as of yesterday, it suddenly stopped working. I'm at a loss as to what might have caused this sudden change. Could someone please offer me some assistance? I've ...

Disabling ESLint errors is not possible within a React environment

I encountered an eslint error while attempting to commit the branch 147:14 error Expected an assignment or function call and instead saw an expression @typescript-eslint/no-unused-expressions I'm struggling to identify the issue in the code, even ...

Debug errors occur when binding to computed getters in Angular 2

Currently, I am integrating Angular 2 with lodash in my project. Within my model, I have Relations and a specific getter implemented as follows: get relationsPerType() { return _(this.Relations) .groupBy(p => p.Type) .toPairs() ...

How to implement a distinct click event for input elements containing a pipe character in Angular

I have developed an innovative Elevator application that features a unique elevator component displaying the current floor value in a box. You can see how it looks here: https://i.stack.imgur.com/h3JW5.png In order to replace the numerical floor values w ...

Utilizing the Bootstrap portfolio section, I aim to eliminate the 'ALL' tab and ensure a category is selected

Currently, I am utilizing this template If you scroll down to the WORK section, you will find the portfolio section which is filterable. The default selected option is "ALL," displaying all items. However, I would like to remove this and activate a diffe ...

Ways to minimize the file size of an Angular2 project

Recently, I started exploring Angular 2 without any previous experience with Angular 1. I came across this tutorial https://angular.io/guide/quickstart and I'm wondering if there's a way to reduce the size of the project. After running 'npm ...

Tips for implementing camera animation to focus on a specific area of a gltf model when it is clicked in three.js

I've successfully used a gltf loader to load a model and implemented a click function on it. The desired behavior is that when a specific part of the model is clicked, the camera should smoothly transition to focus on that part instead of abruptly cha ...

Display a string of text containing multiple interactive links

I have a table and I want to create an interactive effect where, upon mouseover or click of certain elements, text will appear next to it. This text may contain multiple lines and clickable links within the content. For instance, in the table generated by ...

Turn off browser image caching

In order to provide users with fresh weather updates, my Earth weather web application receives new weather maps every six hours as images. I want to prevent the browser from caching these images to ensure that the user always sees the most current data, r ...

How can I maintain the selected state of checkbox and radio button in ReactJS after page refresh?

I am facing an issue with my multistep form that contains radio buttons and checkboxes from material UI. Although the data is stored correctly in state and local storage, when I move to the next page and then return, the selections appear unselected to the ...

The State Hook error "state variable is not defined" arises due to an issue with the state declaration in

function Header() { const [keys, setKeys] = useState([]); //custom addition const first = (e) => { var result = new Map() axios.post('http://localhost:8000/' + query) .then(function(response){ var content ...

"What is the process for developing a Web-component with Vue and typescript that can be used in

Utilizing vue-custom-element, I have successfully created a Web component in Vue and integrated it into Angular. This setup operates seamlessly for Vue+js: import Vue from 'vue' import Calculator from './components/Calculator.vue' impo ...

What is the best way to fetch and convert information from an API to display on a website?

I am encountering an issue while trying to retrieve data from an API. Below is my code with a fabricated access code. $(function () { var $data = ('#data'); $.ajax({ type: 'GET', url: 'http://api.openweathe ...