0

So I have embedded a vimeo video in my Angular 8 app and am now trying to trigger some animation after the video starts playing and once its ended. Essentially if screen width is <800, the variable isMobile is true. Next I have the vimeo play method being called which checks if isMobile is true, and sets load_completed (which is the animation trigger) to true. The isssue is that my variable isMobile returns undefined, why is that?

  isMobile = false;

  constructor() { }

  ngOnInit() {
    this.innerWidth = window.innerWidth;
    console.log(this.innerWidth);
    if (this.innerWidth < 800) {
      this.isMobile = true;
    }

    var iframe = document.querySelector('iframe');
    var player = new Vimeo.Player(iframe);

    player.on('play', function() {
      //isMobile returns undefined why?
      console.log(this.isMobile);
      if (this.isMobile) {
        this.load_completed = true;
      }
      console.log('Played the video');
    });

    player.on('ended', function(data) {
      console.log('Video ended');
    });
  }
felixo
  • 1,453
  • 6
  • 33
  • 60
  • 1
    i think when you are writing it in `function()` `this` is loosing its context so did you try writing an arrow function like `player.on('play',()=>{//your code})` – pavan kumar Dec 01 '19 at 17:18
  • Okay this worked! But why? Isn't this `function()` and this `()=>` the same? just a different syntax? – felixo Dec 01 '19 at 17:23
  • No the reason is when you are using a function that points to a global scope leading to a change of context in this while using an arrow function the context of this is to immediate parent on which the arrow function is called – pavan kumar Dec 01 '19 at 20:49

2 Answers2

2

Try using arrow function as follows , here is the explanation

player.on('play',()=>{
 console.log(this.isMobile);
})
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

You have 2 options here actually.

Arrow functions as mentioned previous answer by default uses this as the this of currently defined place.

Or you can bind the this in the definition of the function

player.on('play',function (){
 console.log(this.isMobile);
}.bind(this));
canbax
  • 3,432
  • 1
  • 27
  • 44