Error: Unable to execute testFunction as it is not defined as a function

I have a unique Vue application with an upload component that allows users to select an image (via dropzone), crop it using cropperjs, and then return the cropped image back to the dropzone. Now, I am looking to compress the image right before uploading it. However, I am encountering an error that is preventing me from progressing further. Here is the current scenario:

Cropping process:

cropImage() {
            // Obtain image data for post-processing, such as uploading or setting image source
            this.$refs.cropper.getCroppedCanvas().toBlob((blob)=> {
                var croppedFile = this.blobToFile(blob, this.fileName)
                croppedFile.accepted = true
                this.$refs.myVueDropzone.dropzone.addFile(croppedFile)
                this.cropperReset()
            });
        },

At this stage, my dropzone correctly displays the cropped images and generates the cropper thumbnail.
Next, I plan to trigger the upload method while compressing the image just before processing the queue.

launchUpload() {
            new Compressor(this.$refs.myVueDropzone.dropzone.files[0], {
                quality: 0.6,
                maxWidth: 250,
                minWidth: 250,
                success(compressedResult){
                    this.testFunction(compressedResult)
                },
                error(err) {
                    console.log(err.message);
                },
            })

            /*await this.$refs.myVueDropzone.processQueue()
            this.$refs.myVueDropzone.removeAllFiles()*/
        }

I pass the file to the Compressor, define certain settings, and expect to receive the "compressedResult" blob, which represents the compressed version of the image. My issue arises when I try to use testFunction within this context:

"Uncaught TypeError: this.testFunction is not a function"

testFunction serves as a placeholder function that I created after exhausting all other options.

testFunction(compressed){
            this.$refs.myVueDropzone.removeAllFiles()
            this.$refs.myVueDropzone.addFile(compressed)
        },

The console.log inside testFunction returns "undefined," indicating that nothing seems to be working properly.
All the methods mentioned here are part of the "methods" object within the Vue component.

This is the section of the Vue code where the components interact:

<v-dialog
            v-model="is_show"
            persistent
            max-width="800px"
        >
            <v-card>
                <v-card-title>
                    <span class="text-h5">Upload File</span>
                </v-card-title>
                <v-card-text>
                    <vue-dropzone
                        ref="myVueDropzone"
                        id="dropzone"
                        :options="dropzoneOptions"
                        @vdropzone-file-added="(file) => passToCropper(file)"
                        @vdropzone-complete="reloadAndClose"
                    ></vue-dropzone>
                    <v-col cols="12" class="text-right">
                        <v-btn
                            @click="closeModal"
                            class="ma-2"
                            :disabled="loading"
                        >
                            Close
                        </v-btn>
                        <v-btn
                            @click="launchUpload"
                            class="ma-2"
                            color="primary"
                            :loading="loading"
                        >
                            Submit
                        </v-btn>
                    </v-col>
                </v-card-text>
            </v-card>
        </v-dialog>

Everything functions smoothly if I skip the image compression step and proceed with processing my dropzone queue immediately after the "addFile" action in the cropImage method.
Thank you in advance for your assistance!

Answer №1

Consider utilizing an arrow function expression instead of a regular function expression. This is because a function expression creates its own this binding.

Therefore, in your scenario, the testFunction does not exist within the new context (the new this).

success(compressedResult){
    this.testFunction(compressedResult)
 },

Observe how this points to the global object when using an arrow function expression and how it refers to the object the method is called on when using a regular function expression:

const obj = {
  someProperty: 'someProperty',
  a: () => {
    console.log(this === window, this === obj)
  },
  b() {
    console.log(this === window, this === obj)
  }
}

obj.a()
obj.b()

If you prefer to stick with a function expression, you can store a reference to this like this:

launchUpload() {
    const that = this;
    new Compressor(this.$refs.myVueDropzone.dropzone.files[0], {
        quality: 0.6,
        maxWidth: 250,
        minWidth: 250,
        success(compressedResult){
            that.testFunction(compressedResult)
        },
        error(err) {
            console.log(err.message);
        },
    })

    /*await this.$refs.myVueDropzone.processQueue()
    this.$refs.myVueDropzone.removeAllFiles()*/
}

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

Executing a mysql select query with the help of Node.js

I'm currently working on a code to check if a player is already registered in a tournament by using their Discord Tag and the Tournament ID. However, the query I created is not returning any results. Thank you. function verifyPlayerNotRegistered(tourn ...

What could be the reason for receiving an "undefined" response in my API ajax

I'm encountering an issue while attempting to call my API using a search term from a submit form. I keep getting an error that says "cannot read properties of undefined." I'm unsure why there is no data being returned when I send the ajax request ...

AngularJS Firebreath Component

Trying to integrate a FireBreath plugin object into an AngularJS view is causing an error when attempting to render the view: TypeError: Cannot read property 'nodeName' of undefined The object can be successfully included in the view using $com ...

Taking in user inputs using Angular 8 reactive forms

My goal is to make my forms function as intended, with multiple forms on each product item having an update and delete option. However, I encountered an issue when adding the [formGroup]="profileForm" directive - the form controls stopped working. This was ...

Tips for concealing the loader once all pages have been loaded

Within the context of my website development project at , I am utilizing a script for infinite scrolling to consolidate multiple pages into one seamless scrolling experience. I am seeking a solution to hide the loader (the spinning icon) when no additiona ...

CORS error: The 'Access-Control-Allow-Origin' header is missing

I have a website that is being accessed through multiple domain names. Let's say the main hosted website is example.com and the forwarded domain names are example-x.com, example-y.com, example-z.com When visitors access the forwarded domains, there ...

Could anyone assist me in positioning my personalized Context Menu beside my cursor?

If possible, I would appreciate some assistance with my custom context menu. It may require some minor tweaks or a fresh idea on how to address the issue. Ideally, I would like to keep the HTML and CSS somewhat unchanged. [I'm not sure what to write ...

Having trouble implementing CORS in a Slim API

I'm facing challenges in setting up CORS with Slim and AngularJS. AngularJS HTTP Request: $http({ method: 'GET', headers: { 'Content-Type': 'application/json', Accepts: 'application/json&ap ...

Contrast between utilizing a WebApp that connects to an API and one that relies on backend

Whenever I develop simple web applications, I often begin by setting up a nodeJS backend, usually creating an API server with ExpressJS. When specific routes are accessed, the server responds by dynamically rendering HTML from EJS based on the current conn ...

Error occurred during the Uglify process: Unable to access the 'kind' property as it is undefined

I developed a project using TypeScript (version 3.9.3) and Node (version 10.16.3), but now I want to minify the code by converting it to JavaScript and running UglifyJS. However, after going through this process, the services that were functioning properly ...

JavaScript recursive reduce function

Looking to filter through an Array of objects and extract only those with the key is_enabled=true from another Array of objects. Structure of the data: [ { 'id': 1, 'label': 'Label1', 'option ...

What could be causing the malfunction in this JavaScript and WebRTC code?

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Vid Chat App</title> </head> <body> <video controls autoplay> </video> <script src="https: ...

What is the best way to conduct synchronous testing of animations in AngularJS version 1.3.15?

Encountering a migration issue with angular-animate.js while transitioning from version 1.2 to 1.3. Here is the animation code snippet: 'use strict'; angular.module('cookbook', ['ngAnimate']) .animation('.slide-down& ...

$scope does not yield any output

While trying to access the $scope variable within my controller, I encountered an issue. When I console log the $scope, it displays a number of values but returns undefined when accessed directly through $scope. I have included a screenshot of the $scope ...

"Download content for offline viewing without the need to create a player object using shaka player

Class: shaka.offline.Storage This class includes a constructor. new Storage(player) Class: shaka.Player This class also has a constructor. new Player(video(non-null), opt_dependencyInjector(opt)) However, my goal is to save a video URL without a vide ...

Component built in ReactJS for file uploads to a server running on Spring MVC/Data-REST

For quite some time, I have been on the lookout for a ReactJS component that enables file uploading from a browser, with the ability to save it to the server where the ReactJS application is deployed. I've come across several components that facilita ...

Tips for effectively retrieving data from the server in Node.js

When attempting to retrieve data using /data with server-side fetch, I encountered the following errors: response.getCategory is not a function (()=>{ const url = "/data"; fetch(url) .then(response => { console ...

A guide to handling deep updates with subdocuments in Mongodb/Mongoose

In this scenario, I am looking to utilize mongoose. Consider a Schema structured like the following: const userSchema = new Schema({ name: { first: { type: String, required: true }, last: { type: String, required: true }, }, email: { type: S ...

Tips on Moving a Bootstrap Modal Popup with the Arrow Keys on Your Keyboard

This example showcases the integration of Bootstrap's Default Modal Popup with jQuery UI Draggable Function. The JS fiddle link provided below contains the code snippet. $(document).ready(function() { $("#btnTest").click(function() { $(&a ...

Check the box by clicking on the label to activate it [Vue.js]

While browsing online, I came across a fantastic tutorial on creating a toggle component on YouTube. https://www.youtube.com/watch?v=J0hp2NF5OzU&ab_channel=LaurentPerrier At the 23rd second mark, the instructor demonstrates that clicking on the label ...