The removeEventListener function is failing to properly remove the keydown event

Every time my component is rendered, I attach an event listener.

 mounted() {
    window.addEventListener("keydown", e => this.moveIndex(e));
}

Interestingly, even when placed within the moveIndex method itself, the event listener persists and cannot be removed. Here's how I am attempting to remove it:

 moveIndex(e) {
    ...
      case 0:
        player.play({
           uri: "https://tv-trtturk.live.trt.com.tr/master.m3u8"
          });
          window.removeEventListener("keydown", e => this.moveIndex(e));
       break;
   ...
}

Despite trying to remove the event listener through a button click event, I encounter the same issue of it not being removed. Am I overlooking something?

Answer №1

removeEventListener states that the listener must be the same:

The EventTarget.removeEventListener() function removes an event listener from the EventTarget that was previously added using EventTarget.addEventListener().

Because

(e => this.moveIndex(e)) !== (e => this.moveIndex(e))
, they are considered different listeners.

The correct way to do it is

window.addEventListener("keydown", this.moveIndex);

and

window.removeEventListener("keydown", this.moveIndex);

Since moveIndex takes e as a parameter and Vue binds methods to component instance, using this.moveIndex as a callback is safe.

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

Information sent to a slot does not trigger a response

Trying to create a mobile-friendly chat app, I want to hide the new message button during conversations and use a different button on desktop. In addition, I have a dialog for creating new chat groups. <v-dialog transition="dialog-top-transition&qu ...

Ways to invoke a JavaScript function using a JSON string

Suppose I make an AJAX post request using jQuery with the following structure: $.post('MyApp/GetPostResult.json', function(data) { // what should be implemented here? }); When the result is as follows: { "HasCallback": true, "Cal ...

Angular 4/5 | Custom Dropdown Component

I have been working on a custom dropdown directive in Angular that I can attach to any DOM element. Below is the code for my directive: import { Directive, HostListener } from '@angular/core'; @Directive({ selector: '[appDropdown]' ...

implement adding a division element to the DOM using the append

I am facing an issue with this particular code. The intended functionality is to create multiple divs in a loop, but it seems to be dysfunctional at the moment. Upon clicking, only one div appears and subsequent clicks don't trigger any response. < ...

Tips on customizing Google Analytics code with Google Tag Manager

My website is currently equipped with the Google Analytics tracking code implemented through Google Tag Manager. The standard Google Analytics code typically appears as follows: <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']= ...

Tips for invoking the href function in jwplayer with individual arguments

I need assistance with configuring jwplayer to load a list of href links one by one. Each href link includes a function that needs to be triggered automatically with specific parameters passed to JavaScript. Below is the code snippet I am currently worki ...

How can I only replace every second occurrence in a JS string?

Looking for help with JavaScript: "a a a a".replace(/(^|\s)a(\s|$)/g, '$1') I thought the result would be '', but it's showing 'a a' instead. Can someone explain what I'm missing? To clarify, I want to r ...

What could be causing a parse error and missing authorization token in an AJAX request?

I recently wrote some code to connect a chat bot to Viber using the REST API. The main part of the code looks like this -: $.ajax({ url : url , dataType : "jsonp", type : 'POST', jsonpCallback: 'fn', headers: { 'X-Viber-Auth- ...

"Sweet syntax" for assigning object property if the value is true

In the project I'm working on, I find myself dealing with a lot of parsing and validating tasks. This often results in 5-10+ lines of code like if(value) object.value = value. I considered using object.value = value || (your favorite falsy value) app ...

Using JavaScript on mobile devices to stream a camera feed to a server

Currently, we are developing an application that requires streaming video recordings to a server. The process flow is as follows: 1) Open a website and activate the primary camera 2) Commence streaming of the camera video to the server 3) Complete the task ...

Guide to Sending and Scheduling Notifications through HTML 5's Notification Web APIs

Is it possible to utilize Web APIs to Schedule Notifications and send them at specific times? I am working on a CMS application that allows users to schedule and send push notifications for their mobile apps. I am interested in implementing something sim ...

Tips on updating a div with jQuery AJAX in my PHP script - help needed!

My jQuery call to PHP is functioning well. However, I am trying to figure out if it's possible to directly output the new content of a specific div from the PHP code using the echo statement. Is this achievable? In the past, I would return the update ...

Ways to retrieve the currently selected id from the router within the next 14 steps

I'm currently trying to extract the ID that is selected (#about, #home, #blog) or the full path (http://localhost:3000/#about, http://localhost:3000/#home) from the router. I am working with Next.js version 14.0.3 This is my approach: My current URL ...

What are the best methods for ensuring a website maintains consistent visibility across all different screen sizes?

Recently, I created a website tailored for a viewport size of 1366px by 768px. My goal is to maintain the same design regardless of the browser window size without implementing responsive design techniques. For instance: When viewing the website on a 360 ...

Looping through data and converting it into a JSON format can

Can anyone help me figure out how to work through this JSON data using VUE? I'm having trouble accessing keys that v-for can't seem to reach: [ { "Lavandería": { "id": 1, "name": "Lavandería", "i ...

Executing a get request in Backbone without using the Option parameter by implementing the beforeSend method

After gathering insights from the responses to this and this queries, I have formulated the code below for a GET request: var setHeader = function (xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa($rootScope.login.Gebruikersnaam + ":" + $r ...

Unable to retrieve data from the array

I am encountering an issue while trying to fetch data from an array, as I keep receiving undefined Please refer to the image for a visual representation of my problem. I'm not sure what I might be overlooking, so any help would be greatly appreciate ...

Animated div or fieldset featuring a multi-step form

I have recently put together a detailed step-by-step guide. Each step is wrapped in its own "fieldset" within a single .html file. To navigate back and forth, I have incorporated javascript into the process. However, as time goes on, I am noticing that th ...

Challenge encountered with AJAX request

Whenever I trigger an AJAX request to a JSP using a dropdown menu, it works perfectly fine. However, when I try to trigger the same request using a submit button, the content vanishes and the page refreshes. function najax() { $.ajax({ url:"te ...

Preventing the occurrence of empty nested arrays within the state

I am currently working on a React Redux application where I am adding movies and including images as a nested array within my object. Here is what my state looks like after adding an item: { movies: [ { "title": "asda", "director": "as ...