Reputation: 241
data: () => ({
showCurrenciesPopup: false,
}),
methods: {
closeCurrenciesPopup() {
this.showCurrenciesPopup = false;
},
escapeKeyListener(event: any) {
if (event.keyCode === 27) {
this.closeCurrenciesPopup();
}
},
},
created() {
document.addEventListener('keyup', this.escapeKeyListener);
},
seems context should be lost here document.addEventListener('keyup', this.escapeKeyListener)
, but not! No any errors, everything works. Does somebody know what is happening?
Upvotes: 2
Views: 214
Reputation: 10187
I think in Vue they attempt to adopt a similar approach than callback auto-bound to the element in traditional addEventListener
:
If attaching a handler function to an element using addEventListener(), the value of
this
inside the handler is a reference to the element. It is the same as the value of the currentTarget property of the event argument that is passed to the handler.
Extract of the section called "The value of this within the handler" on MDN
Except in the case of Vue, they bend the rule a little, it's not auto-bound to the element (document
in your example) but the component.
Upvotes: 0
Reputation: 1446
use bind methods of Function just like this:
created() {
document.addEventListener('keyup', this.escapeKeyListener.bind(this));
},
these are source code of vue, do you understand?
Upvotes: 3