在全局定义的函数中调用函数?

时间:2015-09-23 10:28:26

标签: jquery

我创建了一个暂停youtube视频的功能。当我在定义之后调用函数时它工作正常。

但是如何从其他功能中调用此暂停功能?正如onYouTubeIframeAPIReady在窗口中设置这是否使它成为一个全局函数?那么这应该可以通过它调用我的暂停功能吗?

window.onYouTubeIframeAPIReady = function() {
            $youtubeVideos.each(function () {
              var player = new window.YT.Player(this.id, {
                events: {
                  onReady: function (e) {
                    var state = e.target.getPlayerState();
                    if (state === window.YT.PlayerState.BUFFERING || state === window.YT.PlayerState.PLAYING) {
                      $element.addClass('video-playing');
                      activePlayer = player;
                    }
                  },
                  onStateChange: function (e) {
                    if (e.data === window.YT.PlayerState.BUFFERING || e.data === window.YT.PlayerState.PLAYING) {
                      $element.addClass('video-playing');
                      activePlayer = player;
                    } else {
                      $element.removeClass('video-playing');
                      activePlayer = null;
                    }
                  }
                }
              });

              // Video pause function
              function pauseTheVid() {
                player.pauseVideo();
              }

              // This works 
              $('#trigger').click(function () {
                pauseTheVid();
              });

            });
          };


      // Some other function that is nested somewhere else in my file. 
      // This doesnt work: 
      $('#trigger2').click(function () {
        window.onYouTubeIframeAPIReady().pauseTheVid();
      });

1 个答案:

答案 0 :(得分:0)

// Video pause function
this.pauseTheVid = function() {
    player.pauseVideo();
}

将其更改为对象属性时,您应该能够创建onYouTubeIframeAPIReady的实例并调用该函数。要从同一对象中的其他函数中引用它,您将使用对同一范围的引用。

var self = this;
// This works 
$('#trigger').click(function () {
    self.pauseTheVid();
});

可以使用new创建实例。

window.youtube = function(){
   var self = this;
   this.play = function(){
        console.log('play');
   }
   this.anotherFunction = function(){
        self.play();
   }
}
//use this syntax in whatever file or scope you are
var yt = new youtube();
yt.play();
yt.anotherFunction();

JSFiddle

或者在你的特殊情况下:

  $('#trigger2').click(function () {
    var yt = new onYouTubeIframeAPIReady();
    //pauseTheVid is an object property as told before.
    yt.pauseTheVid();
  });