Angular 4 Error: The function being called is not defined

I'm feeling stuck with my current project. I've come across similar questions asked multiple times in this thread and also here, but none of the solutions seems to fit my specific problem. It seems that the main issue lies in how this is referencing the wrong context. How can I leverage an arrow function to capture the correct this from the declaration site?

drawImageProp(ctx, img, x, y, w, h, offsetX, offsetY) {
    // more code than displayed here
    ctx.drawImage(img, cx, cy, cw, ch, x, y, w, h);
}

onFileSelected(event) {
    for (const file of event.target.files) {
        if (file) {
            const reader = new FileReader();

            reader.onload = function(e: FileReaderEvent) {
                const canvas = <HTMLCanvasElement>document.getElementById('canvas');
                const ctx = canvas.getContext('2d');
                const img = new Image;

                img.onload = draw;

                function draw() {
                    this.drawImageProp(ctx, this, 0, 0, canvas.width, canvas.height, 0.5, 0.5);
                }

                img.src = e.target.result;
            };

            reader.readAsDataURL(file);
        }
    }
}

Answer №1

Implementing a closure:

onSelectFile(event) {
    const self = this;
    for (const selectedFile of event.target.files) {
        if (selectedFile) {
            const fileReader = new FileReader();

            fileReader.onload = function(e: FileReaderEvent) {
                const canvas = <HTMLCanvasElement>document.getElementById('canvas');
                const context = canvas.getContext('2d');
                const image = new Image;

                image.onload = drawImage;

                function drawImage() {
                    self.drawImageProperties(context, image, 0, 0, canvas.width, canvas.height, 0.5, 0.5);
                }

                image.src = e.target.result;
            };

            fileReader.readAsDataURL(selectedFile);
        }
    }
}

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 React's `cloneElement` to make modifications to a child component while maintaining the reference within a functional component

In the past, I had references in my component while rendering, and it was functioning as expected: // props.children is ReactElement<HTMLDivElement>[] const [childRefs] = useState<RefObject<any>[]>(props.children.map(() => createRef()) ...

A dynamic search feature implemented with PHP, MySQL, and AJAX

I have implemented an ajax call to fetch data from my mysql database when searching for users. Below is the corresponding html code; <input type="text" id="partnerName" name="partnerName" class="form-control" placeholder="Type to search partners...."& ...

Enhancing user accessibility can be achieved by either utilizing alt tags on images or aria labels on parent buttons

When using a functional image as a button or link, it is typically marked up with an img tag wrapped by a button tag or anchor tag. If there is no accompanying text for the image, a text alternative needs to be provided for assistive technology. There are ...

Having trouble triggering an alert() after a successful post to the database

As I delve into the realm of backend development, I find myself facing what seems like a simple puzzle that I just can't solve. My goal is to create a basic CRUD app to enhance my skills, so I decided to build a blog platform that could eventually be ...

In the console, a JSON string is displayed, however the PHP variable outputs as null

Below is the snippet of javascript code I am working with: $('.showEditForm').click(function () { var webpagefileID = this.id; if($('#editForm').css('display', 'none')) { $('#editForm').css ...

execute the function within the data() method

I'm currently working on retrieving data for my search tree, and I'm facing issues with fetching the data directly from axios or calling a function because it cannot be found. export default { name: 'SideNavMenu', data () { return ...

Are there any web browsers that automatically switch to a non-SSL connection if an attempt to connect with SSL

I regularly utilize jQuery along with jQuery.ajax to make connections between pages. I am interested in establishing a connection from a non-SSL page to an SSL page using ajax. Are there any web browsers that will attempt to connect via non-SSL if the con ...

Global Declaration of Third-Party Modules for Seamless Use without Imports in Webpack5 with TypeScript

Within my React project utilizing Webpack, I have opted to declare certain modules as global entities to eliminate the need for importing them every time they are needed. In my Webpack configuration file: plugins: [ new webpack.ProvidePlugin({ ...

Having trouble accessing the name property of a select dropdown in Material UI React

Currently, I am facing an issue with implementing a select dropdown. When handling the onChange method, I am encountering a situation where event.target.name is undefined. Specifically, when I choose the 1st option, I want to be able to access 'Englis ...

Using a sequence of array methods like filter, map, and reduce in succession instead of relying on a double loop

Having encountered a perplexing issue that I can't seem to comprehend... here is what I am attempting to achieve. Presented with the following array of objects, products = [ { name: 'Sonoma', ingredients: ['artichoke', 's ...

In a Vue serverless web application, OpenLayers Map object fails to trigger events

In my Vue serverless web application, I have implemented an OpenLayers map initialized in the mounted lifecycle method. The map is populated with ImageWMS layers that are updated by various functions. After updating the parameters of these layers, I call ...

Trigger specific scripts again after loading jQuery AJAX

Is there a way to make specific scripts re-run after an AJAX load is completed? ...

How can I create my own unique scrolling behavior in JavaScript?

Looking to create a similar effect as seen on this website: where the vertical scrollbar determines the movement of the browser "viewport" along a set path. I believe that using Javascript to track the scroll bar value and adjust background elements acco ...

React code to automatically scroll to the top of the page when the user clicks the

Whenever the URL changes or the page is reloaded in my project, I need it to scroll back to the top. While most scenarios work fine, I'm encountering an issue with the browser's back button. Despite a change in the pathname, the page fails to scr ...

Is it necessary to include async/await in a method if there is already an await keyword where it is invoked?

Here are the two methods I have written in Typescript: async getCertURL(pol: string): Promise<string> { return await Api.getData(this.apiUrl + pol + this.certEndpoint, {timeout: 60000}).then( (response) => { return response.data.certUR ...

Is it possible to have a variable either inside quotation marks or NULL when checking for case within a string in JavaScript

The challenge lies in titling this particular question, but demonstrating it is quite straightforward. My goal is to include multiple value sets in an SQL insert statement like the following: var sqlInsertString = `INSERT INTO events (url) VALUES` var sqlI ...

Determine the type of input and output based on another argument

When working with a function that takes an object of either TypeA or TypeB, the first parameter is used to specify the type of the object and the returned type depends on this first parameter. The issue arises in TypeScript where the type of the object is ...

GraphicsMagick operations causing files to become blank

Currently, I am executing the following code: gm(jpgName).setFormat('jpg') .resize(160,158) .compress('JPEG') .write(fs.createWriteStream(jpgName),function(err){ if(err){ console.log(err,jpgName); res.send( ...

Exploring Next.js: Leveraging fetch to retrieve data in getServerSideProps and passing it to the client via query parameters

I'm utilizing a getServerSideProps function on the directory page. pages/catalog/index.js export async function getServerSideProps(ctx) { const response = await fetch( `http://someDomen.com/api/ipro/catalog?${ctx?.query?.page ? `page=${ctx.quer ...

Exploring the process of defining methods within a child Vue component

componentA.vue: <script lang="ts"> import { Vue } from 'vue-property-decorator' @Component export default class ComponentA extends Vue { public methodA(): void { // } } </script> componentB.vue: <template> ...