Vue: using `this.foo()` as a callback function for an event listener

Within the created() hook, I have the code below:

{
  created() {
    window.addEventListener('keydown', this.someMethod)
  }, 
  methods: {
    someMethod(event) {
      console.log(event)
      // perform actions
    }
  }
}

The issue is that the console log is not appearing. Where am I making a mistake? The following solution has proven to be successful:

const someMethod = event => {
  console.log(event)
}

export default {
  ... other content
  created() {
    window.addEventListener('keydown', this.someMethod)
  },
}

UPDATE: It appears there is some confusion surrounding my inquiry. My question does not pertain to using the this keyword within the function, as an arrow function addresses this concern. My query revolves around the inability to pass the object's method as the callback function.

Answer №1

To ensure proper functionality, it is advisable to specify a callback function as the second parameter for the addEventListener method. Utilizing an arrow function within this callback allows for easy access to the this keyword within its scope:

initialize() {
window.addEventListener('mousedown', (event)=>{

    this.executeAction(event)

})
}

Answer №2

The tricky part lies within the following code snippet

created() {
    window.addEventListener('keydown', this.someMethod)
  },

In this scenario, someMethod acts as the function and the entity that invokes it references this.

Now, the query arises regarding the value of this in this context. According to the principle of dynamic scope, a dynamically scoped function will possess the value of this when it is called, not where it is initially defined.

Hence, when the event keydown transpires, it signifies the occurrence and operation based on user input which implies - the value of this would be window, rather than the vue context.

To resolve this issue, we must ensure that this is lexically scoped, indicating that the value of this should reflect the location where the method is authored.

ES6 Arrow Functions serve as a viable solution as suggested in the initial response

created() {
  window.addEventListener('keydown', () => { 
    // The implementation of Arrow functions ensures lexical scoping of `this`.
    // If a standard function is used, then once again it reverts back to dynamic scoping
    this.someMethod()
  })
}

Answer №3

{
  initializeComponent() {
    let view = this // instead of using 'this', assigned it to variable view for eventlistener
    window.addEventListener('keydown', view.handleKeyPress)
  },
}

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

Seeking assistance in understanding how to validate images in Javascript code with the use of Selenium WebDriver. Any t

I am looking to implement the following code to verify if the images on the webpage have loaded successfully. Would anyone be able to clarify how this javascript code actually confirms whether the images are loaded or not? ArrayList<WebElement> imgE ...

Create a card in Bootstrap that adjusts its height based on the response JSON values

I am dealing with a JSON response array structured as follows: var response2 = { "response": { "Data1": [{ codeImage: "605313c59050dc5fc1f3372c" created_by: "23" form_name: "default" ...

What is the true appearance of Ajax?

After spending a few days researching Ajax to use with the Django Python framework, I came across numerous resources on the topic. 1. function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyStat ...

jQuery: Input mask functionality not functioning on field after validation error

My form validation using JQuery is successful. I have integrated a masked input into the birth date field on my form, utilizing the plugin from https://github.com/RobinHerbots/jquery.inputmask. Initially, the birthdate field displays the masked input prop ...

Ways to eliminate the child element(s) from a highlighted text portion

I'm currently struggling to figure out how to manipulate text elements within a span. When a user selects a portion of text in a div, I successfully append a span element. However, if the user selects the same text again, I want to remove the existing ...

How to access a form in Jasmine in AngularJS without relying on $scope

Looking to conduct form testing in Angular, similar to the technique found in this solution. The only difference is that I'm utilizing the controllerAs syntax for my controller (using controller without $scope to reference controller methods). Any ad ...

Can onerror be triggered on an HTML Image onload event?

Having an html image labeled as follows: <image src = 'image.png' onerror = "handleError(this)" onload = "handleLoad(this)"> function handleError(n){ getFirstChild(n.parentNode).style.display = '',n.style.display ...

HTML Client Lightswitch: Assign value to modal picker upon screen initialization

After conducting a considerable amount of research on this issue, I have found that none of the examples provided are helpful or applicable. My goal is to have the Details Picker display a specific name when the Add screen loads, instead of requiring the u ...

The search function in Typeahead is not activating the API request while typing

Having some trouble implementing a typeahead search feature in my nodejs application with mysql. I can't seem to figure out what's wrong with my code. When I manually access http://localhost:5000/search?key=s, I'm able to see the results an ...

I'm looking for a way to add an onclick event to every element created by Vue.js through a "v-for" loop in order to toggle the visibility of its inner content

My Vue data consists of: data: function() { return { results: { "items": [ { "id": "770c257b-7ded-437c-99b5-3b8953b5be3a", "name": "Gsbssbb", "price": 9559, "colour": { ...

How to center a div vertically in a window

I have a CSS layout that positions a div both horizontally and vertically relative to the window. It works well, but when I scroll down the page, the div stays centered as if the page hadn't moved. width:600px; height:300px; position:absolute; left:5 ...

The error "navigator.permissions.query is not a defined object" is encountered in the evaluation

Whenever I try to access my website on an iPhone 7, I encounter a frustrating error. The main screen loads without any issues, but as soon as I click on something, a white bank screen appears. I believe this piece of code might be the cause: useEffect( ...

Function $locationChangeStart in AngularJS not triggering

My code using the $location service in angular seems to be malfunctioning. angular.module("app",[]).run(function($rootScope) { var $offFunction = $rootScope.$on("$locationChangeStart", function(e) { if (confirm("Are you sure")) return $ ...

saving user input as a JSON file

I'm new to JSON and JavaScript and I have created an HTML form. I want to store the data entered by users in a JSON file using JSON objects and arrays. Could someone please guide me on how to do this? This is my HTML form: <!DOCTYPE html> < ...

What is causing the required check to fail even after removing an element?

Can you help me figure out why my required check is not working in autocomplete when using material UI with react hook form? Here are the steps to reproduce: Click on the Submit button, it should show that the field is required. Select any element from t ...

How to create a floating <Toolbar/> with ReactJS, Redux, and Material-UI

Can anyone help me figure out how to make a toolbar floatable when scrolling down using Material-UI? I tried setting textAlign:'center', position: 'fixed', top: 0, but it's resizing strangely when applied to the <Toolbar/>. ...

encountering a type mismatch error while trying to retrieve data from an array

While attempting to retrieve data from a nested array, I encountered the error "TypeError: Cannot read property 'value' of undefined". It seems like I might be calling back incorrectly as I am receiving both the output and the error message in th ...

When using Javascript, the CanvasRenderingContext2D.drawImage function may not properly detect Image data

function ImageLoader() { this.imageBuffer = []; } ImageLoader.prototype.load = function(src) { var temp = new Image(); temp.src = src; this.imageBuffer.push(temp); } Recently, I've been attempting to display a grid of images on the canvas. After deb ...

Don't forget to save and remember the last position of video playback using Jquery

Hello friends, I am looking for PHP/JavaScript/Ajax code that can automatically save the last position of a video into a database (similar to Youtube). Alternatively, if there is code that can store the video time every minute so that visitors can resume ...

React checkbox remains checked even after uncheckingIs this revised version

I am currently working on a React application where I display an array of matches as a list of rows. Each row contains two athletes, and users can use checkboxes to predict the winner for each match. Only one athlete per row can be checked. To keep track o ...