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!