TypeError encountered: attempted to call a private method which is not a function in TypeScript

I've encountered an issue when trying to access a private method within my MyAccount class. The error message that pops up reads:

uncaught typeError: this.displayTabOnClick not a function
. It's worth noting that the method in question is indeed a private one in the MyAccount class, while another similar method called displayTabOnPageLoad functions correctly.

Here's a snippet of the code:

MyAccount.ts file

class MyAccount
{
  private displayTabOnClick(thisObj: JQuery, e:Event, callback?:()=>any): void {
    $(document).scrollTop(0);
    e.preventDefault()
    let hash = thisObj.prop('hash');

    // Update the location hash
    window.location.hash = hash;

    // Add Selected class to the current click elem
    // Remove selected class from other .menu-link elem
    thisObj.addClass('selected');
    $('.menu-link').not(thisObj).removeClass('selected');

    // Set Tab Header
    this.setHeader(hash);

    // Hide all sections
    // And display only the hashed section
    $('section').css('display','none');
    $(hash).css('display','block');
  }

  /**
  * Switch My Account Tab
  * According to the passed ID
  *
  * @return void
  */
  public switchTab (e?: Event): void {
      if (e && e.type === "click") {
          this.displayTabOnClick($('.menu-link'),e);
      }
      else {
          this.displayTabOnPageLoad($('.menu-link'));
      }
  }
}

App.ts file

// My Account Page
let page = new MyAccount;

if (URL.checkPath('/user/myaccount')) {
    page.switchTab();
}

$('.menu-link').click(page.switchTab);

Answer №1

A dilemma arises with the scoping situation when you execute

$('.menu-link').click(page.switchTab);
(this refers back to the caller, not to the page)

Here's one way to resolve it:

$('.menu-link').click(e => page.switchTab(e));

Alternatively:

$('.menu-link').click(page.switchTab.bind(page));

The first option is recommended as it maintains type safety.

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

Using jQuery to set the value of the first option in a Select Box

I need help with a select list: <select id='myList'> <option value="">zero</option> <option value="1">one</option> <option value="2">two</option> <option value="3"& ...

Embracing the jQuery input mask plugin within a Dart Web UI element

I'm facing an issue with integrating an input mask jQuery plugin into a Dart web component. The plugin works perfectly fine when applied to an element outside of a web component, but it fails to function properly within a web component. Interestingly, ...

I'm wondering why my .focus() function is causing the cursor to move to the start of my contenteditable div?

I am currently developing a website for writing books, primarily using php. I have implemented a jQuery function that, upon clicking the "New Chapter" button, triggers an AJAX function along with various other JS/jQuery events. One of these events is inten ...

Implementing the session injection into a request body within an asynchronous function in Node.js

I've been trying to inject a session value into the request in order to use it in various parts of my app. What I'm currently attempting is to call a function by providing an ID to search for a user in the database and retrieve the name of that s ...

Having difficulty accessing information from Firebase database using the .once() function

When a button is clicked on the page, I need to fetch data from a Firebase database using the once() function. Despite setting up the necessary references and variables, the data retrieval seems to be unsuccessful as the global variable numElections keeps ...

Take a snapshot of an element using fixed element positioning

When it comes to extracting a sub image from a webpage using Selenium, I have found a reliable method. First, I capture a screenshot of the entire page and then extract the desired sub-image using the element's coordinates. Dimension elementDimension ...

Looping through children components in a LitElement template

I aim to generate <slot>s for each child element. For instance, I have a menu and I intend to place each child inside a <div> with a item class. To achieve this, I have devised a small utility function for mapping the children: export functio ...

What is the best way to handle the return value from using indexOf on a string?

I am looking to manipulate the value returned by a specific conditional statement. {{#each maindata-hold.[2].qa}} <div class="section"> <a href="javascript:void(0)" class="person-link" id="{{id}}"> <span class="name- ...

Converting a local timezone date object to a UTC timezone date object in JavaScript: a simple and streamlined approach

Looking to convert a Date object with local timestamp to a Date "object" with UTC timestamp. I came across a method that does the job, indeed: var d = new Date(); // creates Date object with local timezone var s_str_utc = d.toUTCString(); ...

ways to forcefully activate the change function

Here is a jQuery function that successfully sends an AJAX request and receives a response: $('#region_id').on('change', function() { //some AJAX request and response which works great. }); The region_id is a select tag contai ...

Utilizing Selenium Webdriver to efficiently scroll through a webpage with AJAX-loaded content

I am currently utilizing Selenium Webdriver to extract content from a webpage. The challenge I'm facing is that the page dynamically loads more content using AJAX as the user scrolls down. While I can programmatically scroll down using JavaScript, I a ...

The issue lies in the error code TS2315 which states that the type 'observable' is not a generic

I keep encountering an error message that says 'observable is not generic' while importing files. I am working on implementing CRUD operations in Angular 7, where I have created two components for adding and listing employees. The functions for c ...

Issues persist with Jquery draggable not functioning properly, part 2

Trying to implement draggable functionality with jQuery on an element, but encountering issues. Here is the code snippet: <html> <head> <link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.cs ...

The sequence of Angular directives being executed

When multiple directives are applied to an element in AngularJS, what determines the order in which they will be executed? For instance: <input ng-change='foo()' data-number-formatter></input> Which directive, the number formatter ...

Adjust website aesthetics through JavaScript by modifying its CSS styling

Hello, in my PHP application I am looking to update the style using JavaScript. <div id="middle-cnt" class="ad-image-wrapper"><div class="ad-image" style="width: 1000px; height: 450px; top: 0px; left: 131px;"><img height="450" width="1000" ...

What factors influence the speed of an Ajax request?

It is common knowledge that the amount of data transmitted to the server, as well as the volume of information returned in a call can greatly affect its speed. However, what I am curious about is whether the following factors might also impact the transmi ...

Dynamically loading various compositions of EDGE

I'm currently working on developing a testing system for edge-animate compositions. The goal is to be able to load different compositions and verify that they are displaying correctly, as well as make changes to their customizable fields. I attempted ...

In the realm of JavaScript, users are restricted to clicking only once

I am looking to convert this code into vanilla JavaScript to restrict the user from clicking more than once, thus preventing duplicate entries in Analytics. jQuery $('.test-link').one("click", function() { $(this).click(function() { ...

Tips for executing multiple function calls within a single React component

Struggling to retrieve information from two separate API calls within the same React component. The issue seems to be with accessing the similar data in the code provided. function Info() { let params = useParams(); const [details, setDetails] = useSt ...

Encountering build issues in my next.js application post updating to version 12.#.# and implementing Typescript

In my next.js application, I recently upgraded to version 10 and added TypeScript to the mix. Despite ironing out all issues during development, I encountered errors when running yarn next build due to my use of the keyword interface. ./src/components/ ...