What is the process for deleting an event in Vue?

My Vue instance currently includes the following code:

async mounted () {
  document.addEventListener('paste', this.onPasteEvent)
},
beforeDestroy () {
  document.removeEventListener('paste', this.onPasteEvent)
},
methods: {
  onPasteEvent () {
    return async (event) => {
      try {
        const items = event.clipboardData.items
        const files = await this.getBase64Files(items)

        this.transferedItems = files
        this.modal = true
      } catch (error) {
        this.$toast.error('Unable to detect a file in the clipboard.')
      }
    }
  },

I am facing an issue with destroying the "paste" event when the component is destroyed. Even though I know I need to use the same reference for removeEventListener, it doesn't seem to work in this case. Could it be that the references are not actually the same?

The only workaround I found was moving the onPasteEvent method outside of the Vue instance as a constant. However, this approach restricts my access to the this instance, which is crucial for me. Additionally, passing arguments becomes impossible with this setup as any attempt seems to create a new reference in memory, preventing the event from being properly removed using removeEventListener.

I am struggling to understand how to remove an event in JavaScript. Can someone provide an example or guidance related to the following questions I have encountered but not fully understood:

  • How do I maintain the method reference even when parameters are involved?
  • How can I successfully remove events while working with Vue instances?

Answer №1

Your implementation for removing the event listener is correct, but there are a few other issues to address:

The function onPasteEvent returns a function, so when the paste event is triggered, it only returns a new function without executing anything useful.

To resolve this problem with the paste event handler, you need to convert the returned function back into the main onPasteEvent function itself:

export default {
  methods: {
    async onPasteEvent (event) {
      try {
        const clipboardItems = event.clipboardData.items
        const filesList = await this.getBase64Files(clipboardItems)

        this.transferredFiles = filesList
        this.modalVisible = true
      } catch (error) {
        this.$toast.error('Could not detect any file in the clipboard area.')
      }
    }
  }
}

If you are using Vue 3, please note that the beforeDestroy hook from Vue 2 has been renamed to beforeUnmount:

export default {
  // beforeDestroy() { ❌ renamed in Vue 3

  beforeUnmount() { ✅
    document.removeEventListener('paste', this.onPasteEvent)
  },
}

Check out this demo for more details.

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

The functionality to scroll to the top of the page is not functioning properly in Next.js when navigating to a new page using the Link

While using Next.js, I encountered an issue where opening a new page would maintain the scroll position from the previous page. For instance, if I had scrolled to the bottom of a product listing page and clicked on a specific product, the product details p ...

"Utilizing Jquery for interactive menu functionality - delivering the requested JSON

I have successfully implemented a dynamic menu using jQuery that parses a JSON response file to create the menu. However, instead of having the menu items link to URLs, I want them to retrieve and parse JSON data from those URLs. Despite my efforts, the me ...

Accessing iframe's HTML using a server-side solution by circumventing the Cross-Domain Policy

Our current challenge involves accessing dynamically generated HTML elements using JavaScript, particularly when trying to extract image URLs from these elements. When the HTML elements are generated solely through JavaScript, extracting the URL is straigh ...

How to confirm the parent state in Angular's UI router?

In summary, I am seeking a function similar to state.is() that can verify a state with multiple child states from one of those child states? This is the structure I have: Parent 1 Child 1.1 Child 1.2 Child 1.3 Parent 2 Child 2.1 ...

The Markdown-to-jsx tool is having trouble processing the provided source code

Utilizing a Material UI blog post template found at https://github.com/mui-org/material-ui/tree/master/docs/src/pages/getting-started/templates/blog, I have created my React app using npx create-react-app. Upon console logging the source, it displays as a ...

How come the index variable doesn't show the index in *ngFor loop in Angular 2?

When working with ng-repeat in Angular 1 to display the index, this code is used: <div ng-repeat="car in cars"> <ul> <li>Index: {{$index+1}}</li> <li>Car Name:{{car.name}}</li> </ul> </div> However, w ...

The RouterView component seems to be malfunctioning within the Vue project

I recently started working on a vue-project where I created a Home page with a sideBar component and a routerView component. Here's a preview: When clicking on any sidebar item, the router navigates to the corresponding path defined in the navigateT ...

A guide on incorporating a method using ES6 Rest into a JavaScript object

My goal is to enhance my Person constructor by adding a method that allows users to add friends. I wanted to utilize the "rest" feature of ES6 to pass a variable number of friends, but I seem to be stuck. My initial attempt resulted in an error ("Uncaught ...

What is the order of reflection in dynamic classes - are they added to the beginning or

Just a general question here: If dynamic classes are added to an element (e.g. through a jQuery-ui add-on), and the element already has classes, does the dynamically added class get appended or prepended to the list of classes? The reason for my question ...

Make changes to external CSS using HTML and JavaScript

Is it possible to dynamically change the value of a background in an external CSS file using JavaScript? Currently, all my pages are connected to a CSS file that controls the background for each page. I am attempting to modify the background by clicking a ...

Changing the size of an iframe and closing it by pressing the ESC

I am developing an application that requires the ability to resize an iframe. When the user clicks the "Full Screen" button, the iframe should expand to occupy the entire screen. The iframe should return to its original size when the user presses the "Es ...

The error occurred while attempting to save the file to disk: 'setHeader() requires both a name and a value to be set.'

I am working on enabling image file uploads to the Node.js server in a MEAN Stack application. Utilizing ng-file-upload for the client-side angular directive has been successful so far. However, I have encountered an issue when attempting to pass the image ...

RTK Query may sometimes encounter undefined values when fetching data

I am new to using Redux and facing an issue while trying to display data in a Material UI Select. When I try to show the user's name, it works perfectly, but when I do the same for the partner's data, they appear as undefined. In my server index ...

Move on to the next iteration in the FOR loop in Node JS

Is there a way to skip item 3 in the loop without breaking it? for (var i = 1; i<= 9; i++) { if (i==3) break; console.log(i); } I had a tough time searching for an answer online because I am unsure of the exact terminology to use. Desired output: ...

A guide on utilizing the React Suite range slider in rsuite

Hello there, I recently started working with the UI framework rsuite (React suite) and everything was going smoothly until I tried to use the Range slider component's API. Unfortunately, I am facing some issues with the labels and tooltips not display ...

Error: JavaScript encountered an unterminated string literal issue

Whenever I try to add the following two lines in the section of my application's homepage, my browser throws a JavaScript error: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script>window. ...

Encountering a 'oembed is null' error in the firebug console while using JQUERY OEMBED

There seems to be an issue with oembed causing an error message in firebug's console window. Specifically, the error is displayed as: oembed is null oembedContainer.html(oembed.code); This error occurs when clicking on a link that leads to the jquer ...

MQTT Broker specialized in Typescript

I'm looking to create a MQTT Broker using TypeScript and Angular. I've attempted a few examples, but I keep encountering the following error: Uncaught TypeError: http.createServer is not a function Here's a simple example of what I'm c ...

How can I change the colors of points on a 3D scatter plot using Three.js as I zoom in?

Seeking assistance with a project involving displaying a 3D point cloud containing approximately 200K points, akin to the image provided below, complete with a colorbar. https://i.sstatic.net/L6ho0.png We are looking to dynamically update the colorbar wh ...

What is the process of exporting ES6 from main.js in Vue.js 2.0?

I've encountered an issue while using the webpack-simple-2.0 template for Vue.js (version 2.0.0-beta.5). When I include export const FOO='bar' in my main.js file, I'm unable to successfully import { FOO } in another .js file - it alway ...