I'm having trouble communicating with my data or methods with this code,
created() {
document.addEventListener( 'touchstart', function( e ) {
this.myData = e.changedTouches[ 0 ].screenY
}
}
I'm guessing that it's because of the function's scope, .this doesn't work inside the function, but then how do I communicate with my data or activate any methods outside of the event listener function then?
You are right this is happening because of this
binding inside the callback which is not pointing the vue instance
To solve this problem define a variable var self = this
in the created hook pointing the vue instance and reference the data property using self
inside the callback
created() {
var self = this;
document.addEventListener( 'touchstart', function( e ) {
self.myData = e.changedTouches[ 0 ].screenY
})
}
Now since the callback has a closure over the variable self
it references the vue instance when it gets invoked
As an alternative you can use arrow functions which bind this
lexically as follows
created() {
document.addEventListener( 'touchstart', ( e ) => {
this.myData = e.changedTouches[ 0 ].screenY
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With