I am quite new to Vue.js. Recently, I have encountered an issue with attaching/detaching keyboard events to window inside one of my ponents. Here are my methods:
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));
},
....
The events attach and fire up without any issues. However, when I switch ponents, the events still remain attached to the window. After a bunch of attempts, I found out that if I remove the .bind(this)
part from all the callbacks, events detach successfully.
Can anyone, please, explain me why this happens?
Thank you in advance!
I am quite new to Vue.js. Recently, I have encountered an issue with attaching/detaching keyboard events to window inside one of my ponents. Here are my methods:
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));
},
....
The events attach and fire up without any issues. However, when I switch ponents, the events still remain attached to the window. After a bunch of attempts, I found out that if I remove the .bind(this)
part from all the callbacks, events detach successfully.
Can anyone, please, explain me why this happens?
Thank you in advance!
Share Improve this question asked Aug 24, 2017 at 20:58 sheriff_paulsheriff_paul 1,0853 gold badges15 silver badges31 bronze badges 1- Bind the method in the constructor instead, each bind return a new function pointer. – T4rk1n Commented Aug 24, 2017 at 21:18
1 Answer
Reset to default 7.bind(this)
returns a new function.
this.processHotkey.bind(this) === this.processHotkey.bind(this)
// => false
That's why removing the listener doesn't work. Lucky for you, that bind is not necessary, because ponent methods are already bound.
So just remove it.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745452109a4628318.html
评论列表(0条)