0

我正在创建一个视频播放器,它依赖于通过 ajax 加载 vimeo 和 youtube 播放列表 api。加载后,对于 youtube,我需要遍历播放列表中的所有视频并调用每个视频的数据 api 以获取其修改日期。一旦加载了所有 vimeo 视频并加载了所有 youtube 视频并有了它们的创建日期,我需要使用 jquery 对它们进行排序。

我正在寻找检测这些过程何时完成的最佳方法,问题是在完成 vimeo 功能和 youtube 功能之前我无法真正开始排序。我能想到的最好的办法是运行一个 setInterval 函数来检查两个布尔标志的状态 - 例如:

var youtubeReady = false, vimeoReady = false;
var videoStatusInterval = setInterval("checkVideoStatus",1000);

function checkVideoStatus(){
  if (youtubeReady === true && vimeoReady === true){
    sortVideos();
  }
}

问题是这只会定期运行(示例中的每一秒) - 一旦满足两个条件,似乎应该有一种方法可以立即执行此操作。有人有想法么?

4

2 回答 2

1

我不熟悉 Youtube 的 API 和 Vimeo,但也许他们有一个“准备好”、“完成”或“加载”事件,你可以听两个,然后,在你设置的处理程序中,你设置两个标志,这样,如果两者都是真的,那么你执行,像这样:

    //Let's createa a couple of custome events to simulate the real ones, comming from Youtube and Vimeo.
var youtube = document.createEvent('Event'),
    vimeo  = document.createEvent('Event');

youtube.initEvent('youtubeReady');
vimeo.initEvent('vimeoReady');

/*
* This function will be use to run YOUR code, ONCE BOTH events are triggered.
* As said, functions are objects so, as any object in JS, you can add fields at any time you want.
* Check this page in Mozilla's Developer Network for more detail:  http://goo.gl/Pdvpk */
function sourcesReady(){
  if(sourcesReady.youtube && sourcesReady.vimeo){
        alert('Both sources ready!');
  }
  else if(sourcesReady.youtube){ 
    alert('Only Youtube ready!');
  }
  else if(sourcesReady.vimeo){ 
    alert('Only Vimeo ready!');
  }
}

//Let's set a couple of event handlers for the 'ready' events, these handlers will set the flags that we need.
document.addEventListener('youtubeReady', function youtubeReadyHandler(){
  sourcesReady.youtube = true; //We set/create the field in the function, that is, the function ITSELF has the field, not the 'this'.
  sourcesReady(); //We call it to evaluate the condition.
}, true);

document.addEventListener('vimeoReady', function vimeoReadyHandler(){
  sourcesReady.vimeo = true; //same as before.
  sourcesReady(); //We call it to evaluate the condition.
}, true);

document.dispatchEvent(youtube);
document.dispatchEvent(vimeo);

希望这个建议有所帮助。=)

于 2013-01-07T16:16:49.440 回答
0

即使这些操作是异步完成的,您仍然可以创建全局变量。

var youTubeScanDone = false, vimeoScanDone = false;

然后将这些变量设置true为完成时。创建一个函数function sortVideoList() { ... },并在每次扫描结束时调用这样的一行

if (youTubeScanDone && viemoScanDone) sortVideoList();

只需确保在调用此行之前将布尔值设置为 true(取决于您所在的扫描功能。

于 2013-01-07T16:20:08.377 回答