Here's my what I'm trying to do:
When my component is mounted, I'm binding events globally on the window with a custom WindowEvents service (such as keydown to capture global shortcuts without having to be focused on the component) and when that specific component is unmounted, those events will automatically unbind themselves.
Here's how I'm actually doing it:
// MyComponent.vue
{
mounted() {
WindowEvents.bind({
keydown: (e) => {
// Keys is a custom service to compare keycodes
if(Keys.check(e.which, "ESCAPE", "ENTER", "RETURN"))
this.submit()
}
})
},
methods: {
submit() {
// will save data and remove this component
}
}
}
Whenever MyComponent is on screen, focused or not, and the user presses either escape or enter, it will call the submit function of MyComponent.
I want that keydown event to be deactivated when the instance of MyComponent is unmounted. right now I'm achieving this by using the onUnmounted lifecycle hook inside the WindowEvents bind method:
import { onUnmounted } from "vue"
class WindowEvents {
static register(events, target) {
return new this({ events, target })
}
static bind(events, target) {
const e = this.register(events, target).bind()
// !! HERE !!
onUnmounted(() => e.unbind())
return e
}
constructor(options) {
...
}
bind() { /* bind events */ }
unbind() { /* unbind events */ }
}
THIS ALL WORKS PERFECTLY
I'm just wondering if this is a bad practice that the vue devs might patch out or "fix" later since I could not find any example in the docs using these lifecycle hooks outside of the component's setup() or the Composition API. If I did do it in the setup(), I wouldn't have access to my component's props or methods such as this.close() used in the keydown event in my example, unless I also set those up in the setup(). But at that point, what even is the point of using the Options API.
In case this stops working, I will just remove the onUnmounted call in the bind method and just manually unbind them in my component:
// in WindowEvents
static bind(events, target) {
return this.register(events, target).bind()
}
// in MyComponent
mounted() {
this.events = WindowEvents.bind({ /* keydown */ })
},
unmounted() {
this.events.unbind()
}
Maybe I'm just trying to min-max my code too much