Proper usage of a method within another method in a Vue component

Currently, I am extracting GPS data from an image using exifjs. My objective is to convert the latitude and longitude variables into a decimal variable as illustrated below:

<template lang="html">
  <div class="upload-wrap">
    <button class="btn">Choose a photo</button>
    <input ref="fileinput" @change="onChange" id="file-input" type="file" accept="image/jpeg"/>
  </div>
</template>

<script>
import EXIF from '../../node_modules/exif-js/exif'

export default {
  methods: {
    toDecimal(number) {
      return number[0].numerator + number[1].numerator /
          (60 * number[1].denominator) + number[2].numerator / (3600 * number[2].denominator);
    },

   onChange(image) {
     var input = this.$refs.fileinput

     if (image) {
       EXIF.getData(input.files[0], function() {

         var lat = EXIF.getTag(this, 'GPSLatitude');
         var long = EXIF.getTag(this, 'GPSLongitude');

         if (lat && long) {
          var lat_dec = toDecimal(lat);
          var long_dec = toDecimal(long);

          // eslint-disable-next-line
          console.log(lat_dec, long_dec);
         }
         else {
          // No metadata found
          clearFileInput(input);
          alert("No GPS data found in image '" + input.files[0].name + "'.");
        }
       })
     } else {
        // eslint-disable-next-line
       console.log(`No image selected?`);
     }
   },
    // Clear file input if there's no exif data
  clearFileInput(ctrl) {
    ctrl.value = null;
  }
 }
}
</script>

Yet, I encountered the following error:

ReferenceError: toDecimal is not defined

I wonder if I am utilizing the correct syntax or missing something crucial?

Edit: I attempted to use this.toDecimal(lat); but it led to

TypeError: this.toDecimal is not a function

Answer №1

If you need to utilize the this.toDecimal method, keep in mind that within the callback function, the this variable does not refer to the Vue instance. You can resolve this by using an arrow function or a small trick involving var self = this.

onChange(image) {
    var input = this.$refs.fileinput
    var self = this;
    if (image) {
        EXIF.getData(input.files[0], function() {

            var lat = EXIF.getTag(this, 'GPSLatitude');
            var long = EXIF.getTag(this, 'GPSLongitude');

            if (lat && long) {
                var lat_dec = self.toDecimal(lat);
                var long_dec = self.toDecimal(long);

                // eslint-disable-next-line
                console.log(lat_dec, long_dec);
            } else {
                // No metadata found
                clearFileInput(input);
                alert("No GPS data found in image '" + input.files[0].name + "'.");
            }
        })
    } else {
        // eslint-disable-next-line
        console.log(`No image selected?`);
    }
}

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

Issue with updating nested child object reference in Redux state input value

I have a function in redux that updates an object with a specified path and value. The inputs on my page are based on the values in the object stored in state. Whenever the listingObj is modified in redux, I want the DOM to automatically refresh. This i ...

How to adjust the size of the text on a button in jQuery mobile using custom

I am facing an issue with my jQuery mobile buttons that are placed inside a fieldset. Specifically, I need to adjust the font-size of one of the buttons. Despite attempting to add an inline style, it did not have the desired effect. Furthermore, I tried u ...

Utilizing Angular's Scope Functionality

I am a novice in the world of AngularJS. Currently, I am delving into the expert's codebase and looking to customize the directives for educational purposes. Interestingly, the expert consistently includes: this.scope = $scope; at the start of eac ...

Angular routing does not properly update to the child's path

I've organized my project's file structure as follows: app/ (contains all automatically built files) app-routing.module.ts components/ layout/ top/ side/ banner/ pages/ ...

Creating an array of strings using data from a separate array of objects in JavaScript/TypeScript

I want to generate a new array of strings based on an existing array of objects, with each object belonging to the Employee class and having a firstName field: assignees: Array<Employee>; options: string[]; I attempted to achieve this using the fol ...

Discover how to use Jest and Enzyme to test for any string as the defaultValue on an input field

As a beginner in the world of testing, I've been exploring the airbnb / jest documentation to troubleshoot an issue with a test. So far, I haven't been able to come up with a solution that actually works. The snapshot contains a defaultValue tha ...

The disappearance of the final element in an array after adding a new one using JavaScript

One of the challenges I'm facing in my backbone project involves creating an Add To Cart feature using window.localStorage. Below is my javascript code for the addToCart() function: var cartLS = window.localStorage.getItem("Cart"); var cartObject = ...

Using Typescript in NextJS 13 application router, implement asynchronous fetching with async/await

Recently, I implemented a fetch feature using TypeScript for my NextJS 13 project. As I am still getting familiar with TypeScript, I wanted to double-check if my approach is correct and if there are any potential oversights. Here is the code snippet from ...

Modifying arrays in ReactJS

Having trouble editing my array list, need some help. I can update a single input value successfully, but struggling with updating the entire array. Any suggestions on why the method isn't working and how to edit the array? When I try to store data ...

What is the most efficient way to transfer a string to a python program using ajax and retrieve a string in return?

I'm experiencing a problem with my ajax request where I am sending an object to a python program using JSON: $.ajax({ url: "http://localhost/cgi-bin/python.cgi", type: "POST", data: JSON.stringify(myobject), dataType: ...

Having trouble showing images from block content using PortableText?

It's been quite a while now that I've been stuck on this issue. Despite being in a learning phase, I find myself unable to progress due to this specific problem. While links and text elements are functioning properly, I have encountered difficul ...

Launching a program through a web browser - a step-by-step guide

I am looking to create a specific sequence of events: A web browser opens, and a user logs in (the exact action is not crucial) The user is then redirected to a new page where another program should automatically open This process is similar to what happ ...

Change the color of the border to match the background color

I have a parent container with a unique background color. Inside the parent container, there is an unordered list (ul) with multiple list items (li), each having a distinct color and a brighter border color. Now, I am looking to extract the border color of ...

Is there a way to create a nested object literal that will return the length of

I am working with JSON data that includes different locations (sucursales) and cars for each location. How can I write a function to calculate the total number of cars across all locations? [{"sucursal": "Quilmes", "direccion&q ...

Ensure that dynamic functions are accurately typed within a proxy utilizing TypeScript

I am currently working on a unique function that utilizes a Proxy with a get trap to extract functions from multiple objects. The challenge I am facing is getting TypeScript to recognize these functions at compile time so that I can add them to my interfac ...

Guide to inserting an HTML file into an article's content

After downloading an extension from freefrontedit and uploading it to my server in the directory /accordeon, I successfully accessed it by pointing my browser to . However, I am now faced with the challenge of loading the index.html into my Joomla article ...

Every time I switch to a new Vue.js route, I find myself inexplicably redirected to the bottom of the page, leaving me scratching my head in confusion

I'm really struggling to understand why this issue is happening because there doesn't seem to be any code that would interfere with the scrolling. Every time I click on the link, it immediately takes me to the bottom of the view. I'm not sur ...

Sending a message to a specific client using socket.io

Currently delving into socket.io + node.js, I have mastered sending messages locally and broadcasting using the socket.broadcast.emit() function - where all connected clients receive the message. My next challenge is figuring out how to send a private mes ...

Obtain an array from an Ajax request using jQuery Datatables

I have integrated the jQuery DataTables Select plugin into my project to enable the selection of multiple rows from a table and storing their data inside an array. Subsequently, I am attempting to make an Ajax Request to pass this array to another PHP file ...

How can I modify an array in Couchbase by using an N1QL query?

{ "name":"sara", "emailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abcde8e2ea9627225c4b9a3afa7bbcc808cb554a1adaf">[email protected]</a>", "subjects" : [{ "name":"Math", "tutor":"alice", "classes" ...