2017-01-24 9 views
0

私はJS、Angular、Meteorを使用してYoutube APIを使用するWebアプリケーションを開発しています。私のコントローラの1つのコンストラクタで、私はYouTubeのプレーヤーのオブジェクトをYouTubeのAPIのプロセスに従って作成します。しかし、同じコントローラー内の後の機能で一見グローバルな「プレーヤー」オブジェクトを参照しようとすると、範囲外に見えます。window.variableNameを使用しなければならない理由がわからない

私はwindow.variableNameを使って嫌になってしまうまで、 "player"変数がグローバルであるように見えるので、この問題は数日間続きました。 window.player = ...を使用すると、playerオブジェクトを認識するためのplayPause関数しか得られません。なぜplayerオブジェクトが、そのコントローラと関数を含むグローバルになっていないのですか?

私はまだJavaScriptスコープの複雑さとECMAクラススタイルの両方を学んでいるので、どんな助けもありがたいです。

マイコード:

import Ionic from 'ionic-scripts'; 
import { _ } from 'meteor/underscore'; 
import { Meteor } from 'meteor/meteor'; 
import { MeteorCameraUI } from 'meteor/okland:camera-ui'; 
import { Controller } from 'angular-ecmascript/module-helpers'; 
import { Chats, Messages } from '../../../lib/collections'; 

export default class ChatCtrl extends Controller { 
    constructor() { 
    super(...arguments); 
    this.currentVideoId = this.$stateParams.videoId; 
    this.chatId = this.$stateParams.chatId; 

    this.isIOS = Ionic.Platform.isWebView() && Ionic.Platform.isIOS(); 
    this.isCordova = Meteor.isCordova; 
    chat = Chats.findOne(this.chatId); 

    if (chat.playerType == "Y") { 
     window.player = new YT.Player('video-placeholder', { 
     videoId: this.currentVideoId, 
     events: { 
        'onReady': this.initTimes.bind(this) 
       } 
     }); 
    } else if (chat.playerType == "V") { 

     var options = { 
     id: this.currentVideoId, 
     width: 640, 
     loop: false 
     }; 

     var player = new Vimeo.Player('vimeo-placeholder', options); 
    } 

    playPauseToggle() { 
    if (player.getPlayerState() == 2 || player.getPlayerState() == 5) { 
     player.playVideo(); 
     this.playPauseValue = "Pause"; 
    } else if (player.getPlayerState() == 1) { 
     player.pauseVideo(); 
     this.playPauseValue = "Play"; 
    } 
    } 

ChatCtrl.$name = 'ChatCtrl'; 
ChatCtrl.$inject = ['$stateParams', '$timeout', '$ionicScrollDelegate', '$ionicPopup', '$log']; 

答えて

1

だから、問題は、あなたのクラスのコンストラクタ内のローカル変数としてプレーヤーを定義することです。したがって、playPauseToggle関数のように、その変数はどこにも表示されません。

代わりに、あなたのプレーヤーをあなたのクラスインスタンスの属性にしてみませんか?

this.player = new YT.Player('video-placeholder'... 

、その後

playPauseToggle() { 
    if (this.player.getPlayerState() == 2 || this.player.getPlayerState() == 5) { 
    ... // replace all occurrences of 'player' with 'this.player' 

この情報がお役に立てば幸い!

+0

ありがとうございました!私はコード内でこれ以外のところでこれを行ってきました。何らかの理由で、プレーヤーを宣言するときに "this"を追加するのを忘れてしまったので、デバッグしようとしても登録されていませんでした。 –

+0

確かなこと - 心配なし! – MacPrawn

関連する問題