Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

communicating with data or methods in vue and addEventListener [duplicate]

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?

like image 397
Kelvin Zhao Avatar asked Dec 02 '22 12:12

Kelvin Zhao


1 Answers

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
  })
}
like image 66
Vamsi Krishna Avatar answered Dec 06 '22 12:12

Vamsi Krishna