首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

构建自定义的 YouTube 播放列表播放器(4)

构建自定义的 YouTube 播放列表播放器(4)

添加控件返回 YouTubePlaylist 对象,并开始添加功能。稍后,您将使用此增强版本的对象来完成在 Web 页面上的播放器。
将六个函数添加到对象:previous()、next()、getCurrentlyPlaying()、setCurrentlyPlaying()、randomize() 和 isRandomized()。previous 和 next 函数被移动到播放列表中的相关视频,如果操作成功,则会返回 true,否则返回 false(也就是说,如果用户在播放列表中的第一个条目时单击 “上一个” 或在最后一个条目时单击 “下一个”)。getCurrentlyPlaying() 将会返回播放列表中当前播放视频的 ID。randomize() 设置或取消设置对象中的 random 属性,isRandomizer() 将会返回 random 属性的值。
清单 6 显示了 Next() 函数。
清单 6. Next() 函数
1
2
3
4
5
6
7
8
9
10
11
next: function() {
   var retVal = false;
   if(this.randomizer) {
      retVal = true;
      this.currently_playing = Math.floor((Math.random() * this.entries.length));
   }
   else if(this.currently_playing <= this.entries.length) {
      retVal = true;
      this.currently_playing++;
   }
   return retVal;




在 Next() 函数中,首先检查是否设置了 random 属性,如果是,则将 currently_playing 索引设置为 entries 数组中的随机值。如果没有设置 random 属性,并且 currently_playing 索引小于数组中的视频数量(也就是还没有通过播放列表中的最后一个视频),那么索引值将递增 1,移动到下一个视频并返回 true,表示操作成功。如果没有成功,则返回 false。
清单 7 显示了 previous() 函数。如果 currently_playing 索引大于零(也就是说,用户正在观看播放列表中除了第一个视频以外的任何视频),则索引递减 1,并返回 true,表示操作是成功;否则将会返回 false。
清单 7. previous() 函数
1
2
3
4
5
6
7
8
previous: function() {
   var retVal = false;
   if(this.currently_playing > 0) {
      retVal = true;
      this.currently_playing--;
   }
   return retVal;
}




在 getCurrentlyPlaying() 函数中,返回 entries 数组中当前播放索引的视频 ID。
1
2
3
getCurrentlyPlaying: function() {
   return this.entries[this.currently_playing].video_id;
}




清单 8 显示了 setCurrentlyPlaying() 函数。给定一个来自当前播放列表的 video_id,将 currently_playing 设置为 entries array 中具有该值的元素的索引。
清单 8. setCurrentlyPlaying() 函数
1
2
3
4
5
6
7
8
setCurrentlyPlaying: function(video_id) {
   for(var index = 0; index < this.entries.length; index++) {
      if (this.entries[index].video_id === video_id) {
         this.currently_playing = index;
         break;
      }
   }
}




在 randomize() 函数是,反转 randomizer 属性的值(从 true 变为 false ,反之亦然)并返回新值。
1
2
3
4
randomize: function() {
   this.randomizer = !(this.randomizer);
   return this.randomizer;
}




isRandomized() 函数返回播放列表的 randomizer 属性的值 — 也就是说,播放列表是否是随机播放的:
1
2
3
isRandomized: function() {
   return this.randomizer;
}

返回列表