sanders
sanders

Reputation: 10898

$emit does not work from an anonymous function

In the mounted hook I have the following anonymous function:

window.onkeydown = function(evt) {
  evt = evt || window.event;

  var isEscape = false;

  if ("key" in evt) {
     isEscape = evt.key === "Escape" || evt.key === "Esc";
  } else {
    isEscape = evt.keyCode === 27;
  }

  if (isEscape) {
    this.$emit("close");
  }
};

However, when hitting the esc button, I get the following error:

app.js:2033 Uncaught TypeError: this.$emit is not a function at window.onkeydown (app.js:2033)

How can I solve this?

Upvotes: 0

Views: 219

Answers (1)

Lassi Uosukainen
Lassi Uosukainen

Reputation: 1688

The function keyword creates a new context for this. To use this keyword inside a function, you can either bind it, assign it to another variable such as var self = this or use an arrow function which does not create a new context.

window.onkeydown = evt => 
{ 
  evt = evt || window.event;
  var isEscape = false;
  if ("key" in evt) {
    isEscape = evt.key === "Escape" || evt.key === "Esc";
  } else {
    isEscape = evt.keyCode === 27;
  }

  if (isEscape) {
    this.$emit("close");
  }
};

Upvotes: 3

Related Questions