Attaching events to the window in Vue.js

Having recently started working with Vue.js, I have come across a problem related to attaching and detaching keyboard events to the window within one of my components. Below are the methods I am using:

created() {
  this.initHotkeys();
},

beforeDestroy() {
  this.discardListeners();
},

methods: {
  initHotkeys() {
    window.addEventListener('keyup', this.processHotkey.bind(this));
    window.addEventListener('keydown', this.removeDefaultBehavior.bind(this));
  },

  discardListeners() {
    window.removeEventListener('keyup', this.processHotkey.bind(this));
    window.removeEventListener('keydown', this.removeDefaultBehavior.bind(this));
  },

....

While the events attach and trigger without any problems initially, they persist even after I switch components. After several attempts, I discovered that removing the .bind(this) part from all the callbacks successfully detaches the events.

I would greatly appreciate it if someone could explain why this behavior occurs.

Thank you in advance!

Answer №1

.bind(this) creates a new function instance.

this.checkUserInput.bind(this) !== this.checkUserInput.bind(this)
// => true

This is the reason why removing the listener does not have any effect. Fortunately, you don't really need to use bind here because component methods are automatically bound.

Therefore, you can simply take it out.

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

Customizing Webpack 4's Entry Point

Below is the layout of my project: -node_modules -src -client -js -styles -views -index.js -webpack.config.js -server -.babelrc -package -package-lock -README.md -webpack ...

AngularJs Controller with explicit inline annotation

I usually inject dependencies using inline annotations like this angular.module('app') .controller('SampleController',['$scope','ngDependacy',sampleController]); function sampleController($scope,ngDependacy) { ...

Replace minor components (SVG) within the primary SVG illustration

I'm interested in transforming SVG elements into the main SVG element. For example, let's say the black square represents the main SVG element. I want to change elements 1, 2, and 3 to different SVG elements using JavaScript code. However, I am u ...

Is the screen size detection malfunctioning when using Vue 3's computed property?

How do I accurately detect screen size in Nuxt 3? I have tried using the code below, but the screen size always shows as 1200. It seems that the computed property is being executed before the onMounted() hook. How can I resolve this issue? <template> ...

When a Bootstrap row has a set maximum height, it continues to occupy space even when its content overflows

There is a div with colors that includes a Bootstrap row with multiple columns. A fixed max-height has been set, giving the appearance of scrollability. However, the row with columns continues to expand well beyond the footer: https://i.sstatic.net/jf3pGx ...

Guide on setting up a configuration node in Node-RED

I am attempting to create a config node similar to this example, but it only displays a text box and not the configuration options. I want the projectid to be a config node, and despite trying various nodes with config setups, nothing seems to work for me. ...

Navigating through JSON data to retrieve specific values and executing repetitive actions

When the form is submitted, I am making an AJAX request to PHP code and this is the response I receive. var data = { "empty":{ "game_sais_no":"Season cannot contain empty value", "game_sc_no":"Category cannot contain empty value", ...

What is the best way to set up a session using jQuery?

I've been troubleshooting my code and I can't seem to figure out why the jquery.session.js file isn't working. Can someone help me find a solution? $.session.set('rmng_time', remaining_seconds); alert("j session "+$.sessi ...

When you try to click outside of react-select, the dropdown doesn't

I've been working on customizing react-select and encountered some issues. Specifically, after modifying the ValueContainer and SelectContainer components, I noticed that the dropdown doesn't close when clicking outside of it after selecting a va ...

MongoDB does not treat aggregate match pipeline as equal to in comparisons

I've been tackling an aggregate pipeline task for MongoDB where I need to retrieve items that do not have a specific user ID. Despite my efforts, I'm struggling to get it right. I attempted using $not, $ne, and $nin in various ways but couldn&ap ...

Issue with dynamically passing select values to pop-up link in Firefox

My website has a select dropdown feature that triggers a confirmation pop up with the same selection when the user makes a choice. Upon clicking Submit, a new window opens with the corresponding link. Everything works smoothly in Safari, Chrome, and Opera ...

Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects Below is the code snippet: this.companyDetailsForm = new FormGroup({ directors : new FormControl(response?.companyDirectors) ...

What is the process for transferring a PDF document to the frontend?

I have a file saved in .PDF format on my computer, and I am attempting to send it to the frontend using node/express. Although I am able to successfully send the file as a binary string stream to the frontend, when trying to download the .PDF onto the use ...

Having trouble getting your AJAX call to function properly? Could be that you're searching for the incorrect

Whenever the button is pressed, I need an AJAX call to be sent to my events_controller#check action. Here's the code snippet: events\new.html.erb: <button id="check-button" type="button">Check</button> application.js: $(document). ...

Canvas with a button placed on top

I am working with a canvas and trying to position an HTML element over it using CSS. My goal is for the button to remain in place on the canvas even when resizing the entire page. Here is the code I am currently using. https://jsfiddle.net/z4fhrhLc/ #but ...

Exploring protractor and webdriver basics in the context of a non-angular application

Currently, I am in the process of writing end-to-end tests for a non-angular application using Protractor. While there is a wealth of information available on how to achieve this, it appears that there are multiple approaches to consider. This has led me ...

How can you obtain constructor parameter from JSON directly within the constructor itself?

I decided to store the fixed parameters required for creating an object in a JSON file as an array. My goal was to have the constructor of the object fetch these parameters from the file. Although reading a JSON file is efficient, I wanted to explore othe ...

Is it better to set a timeout for executing a script in a view, or to incorporate an efficient timeout directly into the

After putting in some effort, I have managed to partially achieve my desired outcome. However, I am still exploring options to improve it further. Here is the situation: There is a controller that displays a view upon successful password reset. Within thi ...

Cross-origin resource sharing working smoothly on Chrome but facing issues on Safari and Firefox

When using my app, logging in works fine on Chrome, but I encounter issues on Safari and Firefox. On Safari, the error message is displayed as seen here: https://i.sstatic.net/Z8QpU.png and on Firefox, the error message is displayed as seen here: https:/ ...

What is the best way to display a component in Blade?

Why isn't my app code functioning properly within Laravel? When I set the address /admin, everything works correctly and displays the admin.blade.php template. However, when I set admin/one, it still shows admin.blade.php but the content of the app is ...