Error: The function this.saveAlpha is not recognized in the current context at eval

This code features a start button, stop button, and a timer. The goal is to retrieve information from the phone using events like DeviceOrientationEvent, which includes properties such as absolute, alpha, beta, and gamma (referenced in this link: here). I'm unsure about the process of handling these types of events since it's unfamiliar territory for me.

Once these events are captured, the data will be stored in an array named orientation[].

<template>
  <q-page padding>
    <div class="text-center text-h5 q-mt-lg">
      {{ $t('tasks.motion.title') }}
    </div>
    <div class="row justify-center q-mt-lg">
      <q-btn
        @click="startTest"
        v-show="!isStarted"
        :label="$t('common.start')"
      />
      <q-btn
        @click="completeTest"
        v-show="isStarted"
        :label="$t('common.complete')"
      />
    </div>
  </q-page>
</template>

<script>
import phone from 'modules/phone'
import userinfo from 'modules/userinfo'
import { format as Qformat } from 'quasar'

const TEST_DURATION = 60

export default {
  name: 'MotionOrientationPage',
  props: {
    sKey: String,
    tId: Number
  },
  data: function () {
    return {
      isSignalCheck: true,
      isStarted: false,
      isCompleted: false,
      timer: undefined,
      totalTime: TEST_DURATION,
      startedTS: undefined,
      completionTS: undefined,
      alpha: []
    }
  },

  mounted: async function () {
     // Events that are running always
     if (window.DeviceMotionEvent) {
       console.log('devicemotion was defined')
        }

     if (window.DeviceOrientationEvent) {
       console.log('GyroScope was defined')
        }
  },

  methods: {
    async startTest () {
      this.isStarted = true
      this.startedTS = new Date()
      this.startTimer()
      phone.screen.forbidSleep()
      if (this.isStarted && this.isCompleted === false) {
       window.addEventListener('deviceorientation', function (event) 
       {
        this.saveAlpha(event.alpha)
        console.log(event.alpha)
       })
      }
    },

     saveAlpha (alpha) {
      this.alpha.push(alpha)
    },

    startTimer () {
      this.totalTime = TEST_DURATION
      this.timer = setInterval(() => this.countDown(), 1000)
    },
    stopTimer () {
      clearInterval(this.timer)
    },

    countDown () {
      if (this.totalTime >= 1) {
        this.totalTime--
      } else {
        this.completeTest()
      }
    },

    completeTest () {
      this.isStarted = false
      this.completionTS = new Date()
      this.stopTimer()
      phone.screen.allowSleep()

      this.isCompleted = true

      // package the report
      const sKey = this.sKey
      const taskId = parseInt(this.taskId)
      const userKey = userinfo.user._key
      let report = {
        userKey: userKey,
        sKey: sKey,
        taskId: taskId,
        createdTS: new Date(),
        startedTS: this.startedTS,
        completionTS: this.completionTS,
        alpha: this.alpha
      }

      this.$router.push({ name: 'reportMotionOrientation', params: { report: report } })
    }
  },

  computed: {
    minutes () {
      return Qformat.pad(Math.floor(this.totalTime / 60))
    },
    seconds () {
      return Qformat.pad(this.totalTime - (this.minutes * 60))
    }
  },

  beforeDestroy: function () {
    this.stopTimer()
    phone.screen.allowSleep()
  }
}
</script>

UPDATE: I encountered an issue with the current code where I receive the error message

Uncaught TypeError: this.saveAlpha is not a function at eval (file1.vue?149e:95)
whenever I attempt to simulate changes in the alpha value from the sensors tab in the browser's developer tools.

Answer №1

I have not had the opportunity to personally try this out, but it seems like the approach would involve adding a listener and then implementing one or more methods to store the new data from the event.

data() {
  return {
     ...,
     values: []
  } 
},
mounted: {
  window.addEventListener('deviceorientation', function(event) {
    this.saveValues(event.alpha)
  });
  // additional event listeners
},
methods: {
  saveValues(value) {
    this.values.push(value)
  },
  // additional saving methods
}

Update based on comments:

...
data() {
  return {
     proceed: "false"
  {
},
methods: {
  ...
  handleListener() {
    if(this.proceed) {
      window.addEventListener('deviceorientation', function(event) {
        this.saveValues(event.alpha)
      });
      // additional event listeners
    }
  }
}

In your component, ensure you have @click=handleListener. You will need to incorporate some logic to control when to start/stop capturing data using the method. Use buttons to toggle the value of the proceed property.

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

Having trouble with passing props in React. Any suggestions on what I might be missing?

It seems like I am facing an issue with passing props in React, and for some reason, it's not functioning as expected. I'm a bit puzzled by the whole situation. Main Application Component import React from 'react' import Produc ...

Utilize external importable modules for webpack Hot Module Replacement in Vue.js by incorporating them from beyond the project

My project has the following structure: . +-- Common | +-- MyCommonVueComponent.Vue +-- MainProject | +-- webpack.config.js | +-- package.json | +-- node_modules | +-- src While building from the console, webpack does not show any errors, indic ...

Keeping the Drawer open in Material-UI: What you need to know!

I am looking to create a collapsible sidebar feature in Material-UI where only the icons are displayed when collapsed. I have successfully implemented the Mini Variant Drawer for the basic sidebar functionality, but I'm facing an issue with maintainin ...

Distinct "namespaces" within HTML

Recently, I've encountered an issue with my application that is causing ID collisions. The application uses AJAX to dynamically load code snippets based on user demand. Although these snippets vary significantly, there are instances where a code snipp ...

Scrollable container with jQuery draggable functionality

I am currently working on implementing a draggable list that I want to contain within a scrollable div. $( ".draggable" ).draggable(); Here is the fiddle I have created for this: http://jsfiddle.net/YvJhE/660/ However, the issue I am facing is that the ...

Storing data values from a specific object key into an array in Vue: Step-by-step guide

Just dipping my toes into the world of Vue framework here. I managed to create a selectable table that stores data in an object. I want this function to run in the background, so I figured it should be in the computed section. The object structure is as fo ...

HTML and JavaScript code to desaturate or grayscale image rollovers without the need for additional image duplicates or sprites

Is there a way to achieve grayscale to color image rollover effects without duplicating images or using sprites? I'm looking for an alternative technique that can accomplish this. Any suggestions on how to implement it? ...

Combining property values based on a common property in an array of objects using JavaScript

I have a large array filled with various objects structured like: [ { "type": "bananas", "count": 15 }, { "type": "kiwis", "count": 20 }, { "type": "bananas", ...

extracting an empty value from this variable

When I click on an anchor tag using this operator, the value appears blank. I have multiple divs with the same class, so I used the .each() function, but I can't figure out where I'm going wrong. The desired output is that when I click on one of ...

JavaScript only collapsible navigation bar

I have implemented a collapsible navbar using Bootstrap 4 framework according to the documentation provided at this link. The navbar and its contents collapse on small screens, including smartphones, by adding the class .collapse.navbar-collapse. You can ...

Looking to swap out the final value in a JavaScript array?

My task involves manipulating arrays. I start with an array of numbers called newArr. The length of this array is used to create another array filled with zeros, which I named zeroArr. const newArr = [1,3,5,8,9,3,7,13] const zeroArr = Array.from(Array(newA ...

What is the best way to incorporate client and server components in nextJS when params and query parameters are required?

I'm having difficulty understanding the client/server component concept in nextJS 14 (using app router). Below is an example page illustrating how I typically structure it and what components are required: I need to extract the id value from params ...

Preventing jQuery from removing child elements while inserting data through ajax

When I try to insert data into an HTML structure using the code below, only one of the elements displays at a time. It seems like when I use Ajax to insert data, the child elements are being removed. How can I prevent this without having to change the stru ...

Using JavaScript, what is the process for getting the value of a child node within Firebase

var ref = firebase.database().ref("games/" + gameId + "/patterns"); ref.on("child_changed", function(snapshot){ var pattern = snapshot.key; console.log(pattern); }); Currently, the code snippet above only logs the key. But how can I extract the player ...

Ways to prevent mouse selection in an input field without disabling or making it read-only

Imagine this scenario: <input type="text"> The task at hand is to prevent text selection within the <input> field. ...

Getting the Request Body Content in Express Middleware

Currently, I am in the process of developing a small API logger to use as an Express middleware. This logger is designed to gather data from both the request and response objects, then store this information in a JSON file on disk for later reference. Her ...

Expanding all rows with the same name in a Vuetify expandable table

I have noticed an issue with the expandable tables in Vuetify, where if two entries in the table have the same name, clicking on one row to expand it also expands another row with the same name. Is there a way to prevent this from happening? To see the pr ...

When passing context to createPage for use in a query, there may be issues if a string is inadvertently converted to a number, causing the query to fail

I am facing an issue with a page creation function that I have implemented. Here is the code snippet: createPage({ context: { productId: String(productId) }, Despite explicitly converting the ID to a string, the page template is still receiving it as a ...

To ensure proper formatting, I must include a comma operator for numbers while typing and limit the decimal places to two

Could someone assist me in formatting a number to include commas and restrict the decimal places to two using regex? I have attempted the following, but need help making it work properly. Currently, when I enter a number it shows up as 1231244, however I ...

Unspecified locale with Next.js router

Despite extensive research and multiple attempts, I have not been able to find a solution to my problem. That's why I am reaching out for help again. Currently, I am working on a local project and I would like to implement Internationalized Routing f ...