最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Binding events to window in Vue.js - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

1 Answer 1

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.

发布评论

评论列表(0)

  1. 暂无评论