-1

This variable is defined inside data:

data () {
  return {
    isSent: false,
    (...)

When trying to call the method here:

methods: {
  sendEmail () {
    let isSent = this.isSent

    const xhr = new XMLHttpRequest()
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText)
        this.isSent = true
(...)

linter says there is an unused variable defined. When I remove the let isSent... initialization, linter says about undefined variable.

I saw the Q&A related to JS closures, but information there, although useful and broad, is very general and doesn't solve more specific issues like this one.

How should I get to the variable from inside the xhr function?

AbreQueVoy
  • 1,748
  • 8
  • 31
  • 52
  • It seems to be in the same scope, so why do you refer to it by this.isSent instead of just isSent ? – Denys Séguret Jul 27 '18 at 11:25
  • Your suggestion to leave out `this` is correct. But the scope is a different one. `sendMail` has another scope than the anonymous func for onreadystatechange. – mbuechmann Jul 27 '18 at 11:27
  • @mbuechmann there are different scopes but the inner one still points to the external one, which means the variables of the external scope are visible. – Denys Séguret Jul 27 '18 at 11:32
  • Updated my answer to be more clear with how it works, and changed the _closure sample_ to show it is not related to your last edit – Asons Jul 27 '18 at 12:07

1 Answers1

1

this isn't what you think it is. Change the function to a arrow function, it should preserve the context of this to be what you expect.

xhr.onreadystatechange = () => {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText)
        this.isSent = true
...

For more information on arrow functions, see the documention on MDN

phuzi
  • 12,078
  • 3
  • 26
  • 50