Interacting with data and functions in Vue using addEventListener

I'm encountering difficulties connecting my data or methods using this code:

created() {
  document.addEventListener( 'touchstart', function( e ) {
    this.myData = e.changedTouches[ 0 ].screenY
  }
}

I presume the issue lies in the scope of the function, as .this doesn't seem to function within it. How can I possibly access my data or trigger any methods outside of the event listener function?

Answer №1

It's important to note that the issue arises due to the binding of this inside the callback function, which does not refer to the Vue instance.

To resolve this issue, you can create a variable var self = this in the created hook to explicitly point to the Vue instance. Then, you can access data properties using self within the callback function.

created() {
  var self = this;
  document.addEventListener('touchstart', function(e) {
    self.myData = e.changedTouches[0].screenY;
  })
}

By creating a closure over the self variable, the callback function will correctly reference the Vue instance when executed.

Alternatively, you can utilize arrow functions, which maintain lexical binding of this, like so:

created() {
  document.addEventListener('touchstart', (e) => {
    this.myData = e.changedTouches[0].screenY;
  })
}

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

How can I extract the width of an uploaded image and verify it using JavaScript?

Is it possible to retrieve the image width through upload using PHP and then validate it in JavaScript? $_FILES['image'] If the image size is not equal to 560px, can we return false and display an alert message using JavaScript? Also, I am won ...

I need assistance with incorporating a datepicker feature using jQuery UI

Can someone please assist me? I am trying to incorporate a datepicker (Jquery UI) and add an additional function in the script for counting, but my understanding of jquery is limited. (My English skills are also lacking, apologies in advance) I would dee ...

Using custom elements within an iteration necessitates the use of 'v-bind:key' directives

Encountering an error in my Nuxt app, it is triggered by the following line: <template v-for="(project, index) in existingProjects"> <span :key="project.projectId"></span> I have attempted to use the :key attribute on the template e ...

What is the best method for animating a display table to none or reducing its height to

My goal is to animate a header whenever the class collapseTest is applied. After some trial and error, I have come up with the following solution: http://jsfiddle.net/robertrozas/atuyLtL0/1/. A big shoutout to @Hackerman for helping me get it to work. The ...

Incorporating Flash videos into an Angular HTML partial using AngularJS techniques

I've been struggling to embed a flash game in an angular HTML partial. The game loads without errors, but when I right click on the blank flash screen, it says "movie not loaded." I have tried using https://github.com/Pleasurazy/angularjs-media and an ...

Implementing MUI createTheme within Next.js

After switching from material-UI version 4 to version 5.5.0 in my project, I encountered issues with createTheme. The colors and settings from the palette are not being applied as expected. Current versions: next: 11.0.0 react: 17.0.2 mui : 5.5.0 theme. ...

The Strapi plugin seems to be encountering an issue as the API is not reachable, leading to a

In an attempt to create a custom API in Strapi backend, I developed a plugin called "test" for testing purposes. However, when trying to access the test response in Postman, it displays a 404 error stating that it is not accessible. Let me provide you wit ...

Passing a form from Blade to Vue in order to utilize the checkValidity method in Vue/Laravel

Here is a custom button made using Vue in a single component. The current issue being faced is how to pass the form to Vue in order to use the checkValidity() method. <template> <div> <input type="submit" class="button_orange button_b ...

The mobile device isn't compatible with Jquery's "read more" feature

Recently, I've encountered some difficulties with the code below. It functions perfectly on desktop but fails to display correctly on mobile devices, showing the entire text instead. Take a look at the HTML section of the code: <span class="more" ...

The error message "TypeError: undefined is not a function when trying to access a resource

I searched online before asking here, but couldn't find a solution. I'm attempting to call a REST service using ngResource, but my app UI isn't launching due to an error: 05-13 02:16:08.011 2402-2402/com.app.mvalt I/chromium: [INFO:CONSOLE ...

Guide to exporting several Chart.JS graphs to a PDF document with each graph on a separate page

I am currently utilizing the JavaScript code provided below to generate a pdf file containing multiple charts. However, all the charts are being placed on a single page. My inquiry is regarding how I can customize the code to have each chart on its own sep ...

Troubleshooting Google Chrome Extension: chrome.storage.sync.get malfunctioning

Could anyone help me troubleshoot my code issue? I successfully save the data, but when trying to load it, the saved data cannot be found: Here is the code snippet: $('#SaveSet').click(function() { var theValue = $('#col').val(); ...

The createAsyncThunk function seems to be failing to trigger in the redux toolkit implementation

Currently, I am tasked with developing an application in React, and the reference application I am using as a guide is located at Below is the code snippet I have been working on in the resourceSlice.js file: import axios from 'axios'; const { c ...

The styled-components in React are having trouble recognizing the HTML attribute 'autoplay' when used with a video tag

I have created a custom styled component for a video tag. const Video = styled.video` ... ` When I use this component like below: <Video width='200px' height='200px' autoplay='autoplay' muted loop> <source src= ...

How can one achieve the equivalent of Flask Safe when making an ajax call?

Having trouble replicating equivalent functions in my Ajax call as I can in regular Javascript on my main HTML page. Using Python/Flask at the back-end. Any similar methods to use the {{ variable | safe }} syntax in AJAX for similar results? My code snipp ...

What could be causing the $httpProvider.interceptors to unexpectedly return an 'undefined' value?

Having some trouble parsing the response of my basic AngularJS app that consumes Yelp's API using $httpProvider.interceptors. This is the structure of my app: var app = angular.module("restaurantList", []); The yelpAPI service handles authenticatio ...

How to properly implement search functionality in a React table?

I recently implemented a search feature for my table in React to filter items fetched from an external API. Instead of making repeated calls to the API on each search, I decided to store the retrieved data in two separate useState hooks. One hook holds th ...

Ensure the md-sidenav remains open by default

I have set up a md-sidenav in my project. I would like the sidenav to be open by default, while still maintaining an overlay effect on the page and allowing users to close the sidenav, thus avoiding the use of md-is-locked-open. Any suggestions on how I ca ...

Disable the second tab within an Angular md-tabs component

Are there any attributes in angular material md-tabs that can be used to disable a tab, similar to what is available in Bootstrap? $scope.tabs = [{ title: 'Dynamic Title 1', content: 'Dynamic content 1' }, { title: 'Dy ...

Using Vue/Nuxt.js to compute the cumulative sum of hierarchically structured JSON data

When using Nuxt async data, I am retrieving a JSON object that includes a nested array in the following structure: "topic_list": { "topics": [ { "id": 9148, "title": "A", "views": 12 }, { "id": 3228, ...