Rodion Golovushkin
Rodion Golovushkin

Reputation: 241

Why isn't context missed when I pass callback in vue?

  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

Answers (2)

Delapouite
Delapouite

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

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#The_value_of_this_within_the_handler

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

jacky
jacky

Reputation: 1446

use bind methods of Function just like this:

created() {
    document.addEventListener('keyup', this.escapeKeyListener.bind(this));
},

enter image description here

enter image description here

these are source code of vue, do you understand?

Upvotes: 3

Related Questions