Reputation: 63
I added a event listener to my document like this:
deleteTask(event){
// myFunc
}
created() {
document.addEventListener("keypress", this.deleteTask);
},
This happened in my Home.vue component. Now i want to remove this event listener in my Card.vue component. Like so:
document.removeEventListener("keypress", this.deleteTask);
This obviously doesn't work since this.deleteTask is not known in the Card.vue component. But i need the deleteTask func to stay in my Home.vue cause it operates on some arrays there. So my question is now: What is the best way to do this?
Upvotes: 2
Views: 2536
Reputation: 1125
You could create an EventBus.
Create a new js
file with:
import Vue from 'vue';
export const EventBus = new Vue();
Now you can in your Home.vue listen to events:
created() {
...
EventBus.$on('removeListener', () => { document.removeEventListener("keypress", this.deleteTask); })
}
The event removeListener
will then be called in Card.vue using EventBus.$emit('removeListener')
Upvotes: 1
Reputation: 2487
Don't make it global, let it to listen only in your component:
<template>
<div @keypress="deleteTask">
...
</div>
</template>
Upvotes: 0