senty senty - 1 year ago 43
Javascript Question

Data is not recognised inside setTimeout inside another closure

I have my data, and I am trying to access it within an initializer inside setTimeout.

data() {
return { val: {} }
},

methods: {
test() {
console.log(this.val) // works

var self = this

setTimeout(function() {
console.log(this.val) // works
var check = this.myMethod()

$.validate({
onError: function($form) {
console.log(self.val) // doesn't work
}
})

}, 500)
},

myMethod() {
// some stuff
return true
}
}


This is the updated code. Using the
var self = this
approach, I am now gettign:


Uncaught TypeError: this.myMethod is not a function

Answer Source
data() {
    return { val: {} }
 },

 methods: {
    test() { 
         console.log(this.val) // works
         var self = this;
         setTimeout(function() {
              console.log(self.val) // works                 

              $.validate({
                   onError: function($form) {
                        console.log(self.val) // doesn't work       
                   }
              })

         }, 500)
    }
 }

Try this. You often lose the value of this when calling functions within functions, so we store this in a variable to make it accessible from nested functions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download