javascript – accessing class data in a function in global scope with typescript

Question:

I'm developing an application in Angular 2 and I'm using the Youtube API. The Youtube API requires me to implement some functions at global scope, so I did the following:

export class MyClass {

  dados: any;

  constructor( ... ) {
    ...
  }

  loadAPI(){
    (window as any).onYouTubeIframeAPIReady = function () {
      buildPlayer();
    }

    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    console.log('API loaded');
  }

}

function buildPlayer(){
  player = new YT.Player('player', {
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
  console.log('youtube iframe api ready!');
}

function onPlayerReady(event){
  // AQUI ESTÁ O PROBLEMA
  // Eu quero manipular "dados" dentro dessas funções.
}

function onPlayerStateChange(status){
  // AQUI ESTÁ O PROBLEMA
  // Eu quero manipular "dados" dentro dessas funções.
}

The code loads the API correctly and creates the player, but I can't manipulate the variable data that is inside the class in these functions. Any idea how I can fix this?

Answer:

The problem is that the dados variable is part of the class scope and these functions are declared outside the class , just adjust that.

Declaring the data variable outside the class will allow it to be accessed outside the class.

dados: any;

export class MyClass {    

    constructor() {

    }

    loadAPI(){
    (window as any).onYouTubeIframeAPIReady = function () {
      buildPlayer();
    }

    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    console.log('API loaded');
    }
} 

function buildPlayer(){
  player = new YT.Player('player', {
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
  console.log('youtube iframe api ready!');
}

function onPlayerReady(event){
    //a variável dados pode ser acessada aqui
    console.log(dados);   
}

function onPlayerStateChange(status){
    //a variável dados pode ser acessada aqui
    console.log(dados);        
}   
Scroll to Top
AllEscort