admin管理员组文章数量:1425780
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.
本文标签: javascriptBinding events to window in VuejsStack Overflow
版权声明:本文标题:javascript - Binding events to window in Vue.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745452108a2658934.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论