Why is the defined function not being called in this Typescript nested this situation

Currently, I am in the process of developing an app with Ionic 2 Beta and Typescript. I have encountered an error related to how this is used within nested functions in Typescript. Despite my efforts, I am struggling to understand it fully. Below you will find a snippet of my code:

constructor(public navCtrl: NavController, params: NavParams, platform: Platform) {
    platform.ready().then((readySource) => {
        try {
            this.num = params.get("num");
            this.unprocData = params.get("data");
            var image = <HTMLImageElement>document.getElementById('unprocImg');
            image.src = this.unprocData;
            image.onload = function() { console.log("images loaded"); this.proc(this.num); }
            //some stuff
        } catch (err) {
            console.log("Problem Starting Render // " + err);
            this.navCtrl.push(IndexPage);
        }
    });
}

proc(num) {
    try {
        console.log("starting render...");
        switch(num) {
            case 0:
                this.procImg1(function() { //process the image for default vintage greyscale  
                    this.load(this.procData, this.descriptionPoster1, "assets/img/Poster1.png", 250, 310, .6, .6);
                }); break;
            ..
        } 
    } catch (err) {
        console.log("Problem Starting Render // " + err);
        this.navCtrl.push(IndexPage);
    }
}

test() {
    this.proc(0);
}

Interestingly, the function test() performs as expected. However, when I call this.proc(..) from within image.onload(), I encounter the error message stating that this.proc is not a function. How can I overcome this issue? Your insights are highly appreciated. Thank you.

Answer №1

The issue arises from the fact that the this changes in this scenario:

image.onload = function() { console.log("images loaded"); this.proc(this.num); }

This happens because the regular function being used does not retain the context of this when it is executed (it's asynchronous).

You have a couple of options:

(1) Utilize an arrow function like you did previously:

image.onload = () => { console.log("images loaded"); this.proc(this.num); }

(2) Use bind:

image.onload = function() { console.log("images loaded"); this.proc(this.num); }.bind(this)

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

Event Stencil Emitter Unclear

I am in the process of developing a web component using stencil and react. The issue I am facing is that even though the value is emitted, it appears as undefined when called within the component. @Event() newModuleClicked: EventEmitter<any>; ...

Load various types of classes and run functions with matching names

I have encountered a challenging issue that needs to be resolved. Imagine having multiple classes located in a directory named services. These classes all include a constructor() and send() method. Examples of such classes can be Discord, Slack, SMS, etc. ...

Troubleshooting: ReactJS CSS Class Issue

I'm fairly new to working with ReactJS and I've encountered an issue while trying to create a class for a specific form. Below is the code I've written: import React, { Component, PropTypes } from 'react'; import s from './s ...

json data hidden from sight in jQuery

Snippet of HTML Code: <select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);"> <option value="">--Select--</option> <option value="Value11">Value1</option> <option value="Value2">Value2</op ...

Guide for transforming a list of items into nested structures based on a key comparison

Objective: The goal is to organize the list of objects into a nested object structure based on their parent values. Here is the json data provided: "data": [ { "id": "coding-825x500", "source": { "information": { "fileid ...

Collect data from a third-party website that necessitates the activation of JavaScript

Given that phantomjs has been abandoned, I am exploring alternative methods. For instance, using chrome-webdriver may not be ideal as it cannot operate on a remote host like heroku. Is there a way to scrape a website that relies on JavaScript being activa ...

Tips for Implementing the `otherwise` Function in Angular 2's UI-Router

When working with ui-router in AngularJS, we can use the otherwise function to handle invalid or unregistered states. For example: $urlRouterProvider.otherwise('/index'); This means that any invalid URL will be redirected to /index. But how do ...

Exploring ways to validate the existence of a class in HTML table elements

If I want to verify if each element has a specific class when creating tables and clicking on the corresponding cells above them, This is what I have tried. However, it did not work as expected. How can I make this work correctly? What am I missing her ...

The parameter type 'E' cannot be assigned to the type ' { [s: string]: unknown; } | ArrayLike<unknown>' is the argument in question

Recently, I've been attempting to update a library that utilizes this function to the newest version of Typescript: /** * This function takes an array of entities and maps their property values into arrays * keyed by the name of the property in eac ...

Issue with Node.js connection to MySQL database resulting in timeout error (ETIMEDOUT)

I am attempting to establish a basic connection to an online mysql database using a node.js server. Here is the code I have written for this purpose: var mysql = require('mysql'); var con = mysql.createConnection({ host: 'example.org& ...

Vue text failed to display the variable. Any ideas on why?

While working with a library, I encountered the issue of having "Close {{myVar}}" displayed on the screen. Can anyone guide me on how to use template literals in Vue? I have experience with React JSX. <template> <a-alert message="Info Tex ...

disabling focusOnSelect in slick.js arrow controls

I am currently using the slick.js menu with focusOnSelect: true. However, I have noticed that when I click on the left and right arrows, the colors of the divs are also changing. Is there a way to prevent this color change when clicking on the arrows? Can ...

Troubleshooting a jQuery Selector Issue with a Dynamic Form

I developed a jQuery function to search for all the necessary inputs in a specific section of a website. function check_property_vars() { jQuery(this).parents('.property_group').find('div[id^="property_group_"]:input[required]:visible&a ...

Next13, varying data retrieval outcomes between server and client

Embarking on a project with Next13 has been smooth sailing so far. However, as a beginner, I am puzzled by the discrepancy in results I am obtaining from fetching data. Despite setting the component to render on the client side, it also renders on the serv ...

Is there a way to execute Angular code synchronously similar to how it is done in C#?

Trying to replicate a C# application in Angular is proving to be challenging for me, particularly when it comes to ensuring that the code runs synchronously. Consider the following example: private void doChecks() { if (isInvoiced()) return; ...

Is there a method to eliminate the necessity of including the server IP address in the nginx configuration file?

I integrated nginx as a reverse proxy into a basic express app. In the configuration file, I specified the server IP address () as the server_name. However, I am looking for a way to avoid directly inputting the actual server IP in the config file without ...

Store the XML data extracted by JSDOM in a separate file

When it comes to parsing XML, here is an example: import JSDOM from "jsdom"; const myXml = "...xml code goes here..."; const dom = new JSDOM.JSDOM(myXml); I found it surprising that when I searched for "jsdom save xml", there were no relevant results. Co ...

Tips for choosing an ID in Jquery to use in an if statement

I'm trying to create a form selector that will display different outputs depending on the selected option. However, I'm having some trouble getting it to work. Below is my current code: <!doctype html> <html> <head> <meta ch ...

Attempting to extract a specific item from an <li> element and then transfer that data into a text input field

Need help with a javascript issue involving an input box and a list of addresses. <input type="text" id = "addressbox" size="30" onkeyup="showResult(this.value)"> <ul class="livesearch" id="livesearch" style="border: 1px solid rgb(165, 172, 178) ...

Unraveling the Perfect Jest Stack Trace

Currently, I am in the process of debugging some tests that were written with jest using typescript and it's causing quite a headache. Whenever a test or tested class runs Postgres SQL and encounters an error in the query, the stack trace provided is ...