Reputation: 376
I want to change (reset) a data property after a certain time. My try resulted in an type error: Cannot set property 'showSuccessPopover' of undefined
This is the code:
data() {
return {
showSuccessPopover: false,
}
},
methods: {
evaluateAnswer():void{
//fancy evaluationstuff happening
showSuccessPopover = true;
//reset popover after 2s
setTimeout(function() {
this.showSuccessPopover = false;
}, 2000);
}
}
Im more familiar with JAVA than with typescript, so my guess is that internally Java is running sleep or something similar inside another thread, which is why it craches when trying to access the showSuccessPopover on itself(because the field dosnt exist inside the thread object) - thats only my guess of what's happening please feel free to correct me if things are different, I'd actually like to know.
And a way on how to tackle my problem of course ;)
Thanks in advance!
Upvotes: 0
Views: 210
Reputation: 456
This happened because within a function()
, the keyword this
refers to the function itself (which can be an object) to which is undefined, in order to refer to its immediate parent (which is the vue instance we need), you need to convert it to an arrow function like so
<!-- language: lang-js -->
setTimeout(() =>{
this.showSuccessPopover = false;
}, 2000);
Also here is a useful resource for JavaScript with some of the best articles and exercise I have come across.
Upvotes: 1