5

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?

Kelvin Zhao
  • 2,243
  • 3
  • 22
  • 31

1 Answers1

17

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
  })
}
lenooh
  • 10,364
  • 5
  • 58
  • 49
Vamsi Krishna
  • 30,568
  • 8
  • 70
  • 78