ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

RepeatYT: Youtube Repeat

Updated on April 11, 2016

RepeatYT

Undestanding Knockout Javascript library with a youtube repeat design

This document is created to show a design of complete playlist application using Knockout javascript libraries.

Youtube is the biggest video sharing website. But its UI is not much user friendly. It doesn’t even has a repeat option for videos and playlist management is also not straightforward. So I had created a youtube playlist managing website using KnockOut js. You can check it at ‘Youtube-Viewer.com’.

The functionalities that I have implemented are:

  • You can Add a Youtube Video to the Playlist by entering the URL and clicking on the “Add Video” button
  • You can Move a video up and down in the playlist by clicking “Move Up” or “Move Down” link
  • You can Remove a video from the playlist by clicking “Remove Video” link.
  • You can Remove All videos by clicking Remove All button
  • You can turn Repeat On or OFF by clicking Repeat button
  • All the playlist changes that you do will be saved in cookies and whenever you visit again then it will start form the point you last left it

I had used Knock Out JS libraries to create it. Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.

Understanding Knockout JS

Knockout JS is based on binding between the UI and the ViewModel.

ViewModel is the data structure that will hold the data and all the data are directly binded to the UI.

You don’t have to worry about displaying a variable if it is directly binded to data in view model.

Example

Suppose this is a view model


function AppViewModel() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);

}
// Activates knockout.js
ko.applyBindings(new AppViewModel());

And it is binded to the UI

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<p>Full name: <strong data-bind="text: fullName"></strong></p>

So here the AppViewModel is our data structure and contains thee fields: firstName, lastName and fullName. These are directly binded to the UI.

UI has two input fields and first is binded to firstName and second is binded to lastName. Note that value part of the input tag is binded to the fields. The next tag of UI that is binded is strong. Note that the text part of the strong is binded to the fullName field.

Now whenever you will change anything in any of the two input field then KO will evaluate the fullName and display it. So this is a very clean approach in which we have data models and we have UI with are binded together.

DataModel of my playlist

I have created a ViewModel to store the data and the functions.

  • I have created a Video class: a simple JavaScript class constructor that stores details of one Video
  • And ViewModel that has an array of Videos. I have added two Videos to initialize the videos array. Then the ViewModel contains other fields to hold the current state of the player, like current video name, current repeat mode, etc.

Creating a class Video

function Video(name,desc, urlof) {
var self = this;
self.index = ko.observable(1);
self.name = ko.observable(name);
self.desc = ko.observable(desc);
self.urlof = ko.observable(urlof);
self.playing = ko.observable("0");
var index = urlof.indexOf("v=");
var imgsrc = "http://i.ytimg.com/vi/"+urlof.substring(index+2)+"/default.jpg";
self.isrc = ko.observable(imgsrc);
}

Creating a ViewModel

function ViewModel() {

var self = this;

this.videoName=ko.observable("");

this.videoUrl=ko.observable("");

this.repeat=ko.observable("repeatoff.png");

this.loaded=ko.observable("0");

self.videos = ko.observableArray([

new Video("Blue","Description of blue", "http://www.youtube.com/watch?v=h2S3RvIHwGs"),

new Video("Orange","Description of orange", "http://www.youtube.com/watch?v=4u6RK87e0rQ")

]);

Binding the Videos array to the table to display each video details

Then we have binded the videos array to a table. The table will automatically create rows for each of the video in the array because of the binding. Then inside tags are binded to the name, description etc field of the Video object to display the details of each object.

<tbody data-bind="foreach: videos">

<tr>

<td ><img alt="" data-bind="attr: { src: isrc}"/>

<a data-bind="text: name" id="videolink" style="margin-top: 2px;"></a>

<p style="height: 30px;overflow: hidden" data-bind="text: desc" ></p>

</td>

</tr>

</tbody>



Here the foreach:videos is used to bind the array to the table. One tr element is created for each array element. Inside that we have binded the image source isrc to the img tag’s src attribute. We have binded name field of Video object to the a tag’s text attribute and the desc field of view model to the text attribute of p tag.

Adding a video to the Videos array

I have created an input for getting the video url to add a video.

<input type="text" placeholder="Enter the youtube url..." data-bind="value: videoUrl" />

The value of this input is directly binded to the videoUrl field of ViewModel and this field will be used to invoke the youtube api to get the video details when the Add Video button will be clicked.

I have added a button which when clicked will add the video to the array.

<input type="image" src="AddVideoButton.png" data-bind="click: addVideo" eight="36" style="width: 120px;height: 36px;text-align: left;padding: 0px 0px 0px 0px;">

This image has its click attribute binded to a function addVideo. Whenever the button will be clicked then the function addVideo will be called.

self.addVideo = function() {

var vidurl=this.videoUrl();

var index=vidurl.indexOf("v="); vidurl="http://gdata.youtube.com/feeds/api/videos/"+vidurl.substring(index+2)+"?v=2&alt=jsonc&callback=?";

$.getJSON(vidurl, function(data) {

var index=data.data.player["default"].indexOf("&feature");

var url=data.data.player["default"].substring(0,index);

self.videos.push(new Video(data.data.title,data.data.description, url));

});

this.videoName("");

this.videoUrl("");

}

The function addVideo is taking the videoUrl() of the ViewModel and calling the youtube api to get the video details. Then it is pushing the video details received in the array at the end.

Removing a video from the Videos array

I have given a link with each video to remove the video from the list.


<tbody data-bind="foreach: videos">

<tr>

<td ><img alt="" data-bind="attr: { src: isrc}"/>

<a data-bind="text: name" id="videolink" style="margin-top: 2px;"></a>

<p style="height: 30px;overflow: hidden" data-bind="text: desc" ></p>

<a href="#" data-bind="click: $root.removeVideo" style="float: none;">Delete</a> |

</td>

</tr>

</tbody>

Here the click attribute of the a tag is directly binded to a function removeVideo. Whenever it is clicked then the below function will be called.

self.removeVideo=function(Video){

if(Video.playing()!="1")

{

self.videos.remove(Video);

}

else

{

if(self.videos().length==1)

{

self.videos.remove(self.videos()[0]);

ytplayer.stopVideo();

}

else

{

self.playNextVideo();

self.videos.remove(Video);

}

}

}

The functions checks that if the video is not the current playing video then it removes the video direclt from the list. And if the video is the current palying video then it removes the video and plays the next video in the list and if there are no more videos in the list after removal of it then it stops the player.


Removing all videos from the Videos array

I have added a button to remove all the videos in one go.

<input type="image" src="remove.png" data-bind="click: removeAll" eight="36" style="width: 200px;height: 36px;text-align: left;padding: 0px 0px 0px 0px;">

The click attribute of the button is binded to the removeAll function below.

self.removeAll=function(){

var length=self.videos().length;

for(var i=0;i<length; i++)

{

self.videos.remove(self.videos()[0]);

ytplayer.stopVideo();

}

}

The function removes each of the video from the list and then stops the player.



Playing a video from the Videos array

I have added a link with each video which when clicked will play that video.

<tbody data-bind="foreach: videos">

<tr>

<td ><img alt="" data-bind="attr: { src: isrc}"/>

<a data-bind="text: name" id="videolink" style="margin-top: 2px;"></a>

<p style="height: 30px;overflow: hidden" data-bind="text: desc" ></p>

<a href="#" data-bind="click: $root.playVideo" style="float: none;">Play</a> |

<a href="#" data-bind="click: $root.removeVideo" style="float: none;">Delete</a> |

</td>

</tr>

</tbody>

Here the click attribute of the a tag is binded to the playVideo function below.

self.playVideo=function(Video) {

var index=Video.urlof().indexOf("v=");

var vidId=Video.urlof().substring(index+2);

ytplayer.loadVideoById(vidId, 0, "large");

var length=self.videos().length;

for(var i=0;i<length; i++)

{

self.videos()[i].playing("0");

}

Video.playing("1");

}


The function gets the index and url of the video requested to be played from the data bind. Then it uses the youtube api to play the video. And then it changes the playing status of the last played video to 0 and changes the playing status of currently playing video to 1.


Play next video from the Videos array

I have created a function playNextVideo which runs through the video array and finds the video which has current playing status as 1. Then it goes to the next item in the array and sends it as input to the previously described function playVideo to play it.

self.playNextVideo=function(){

var length=self.videos().length;

var videoIndex=-1;

for(var i=0;i<length; i++)

{

if(self.videos()[i].playing()=="1")

{

videoIndex=i;

}

}

if(videoIndex>=0)

self.playVideo(self.videos()[(videoIndex+1)%length]);

}



Play previous video from the Videos array

I have created a function playPreviousVideo which runs through the video array and finds the video which has current playing status as 1. Then it goes to the previous item in the array and sends it as input to the previously described function playVideo to play it.

self.playPreviousVideo=function(){

var length=self.videos().length;

var videoIndex=-1;

for(var i=0;i<length; i++)

{

if(self.videos()[i].playing()=="1")

{

videoIndex=i;

}

}

if(videoIndex>0)

self.playVideo(self.videos()[videoIndex-1]);

else if(videoIndex==0)

self.playVideo(self.videos()[length-1]);

}


Setting the Repeat mode

I have added a button to set the Repeat mode On and Off. Initially it is in off state. When user will click it then it will toggle between on and off states. It uses images “repeaton.png” and “repeatoff.png” as sources to display the state.

<input type="image" id="repeatbutton" data-bind="attr: { src: repeat }, click: setRepeatMode" eight="36" style="width: 100px;height: 36px;text-align: left;padding: 0px 0px 0px 0px;">



Here the attribute src of the image is bind to the repeat field of the ViewModel which contains either the image of Repeat On or Repeat Off. The click attribute is binded to the setRepeatMode function below.

self.setRepeatMode=function(){

if(this.repeat()=="repeatoff.png")

{

this.repeat("repeaton.png");

}

else if(this.repeat()=="repeaton.png")

{

this.repeat("repeatoff.png");

}

}


The function checks the current value in the repeat field of ViewModel. If it is “repatoff.png” then it changes it to “repeaton.png” and vice versa.


Checking for player state to change video or repeating it

This is a timed function of javascript which checks the video player state after interval of 3 seconds. It checks that the video has ended or not. Then it checks the value of the repeat field of ViewModel to get the repeat mode. If the repeat mode is on then it plays the same video again and if the repeat mode is off then it calls the palyNextVideo function that I have described above.

The function also loads the current state of the playlist in a cookie. The setCookie function is at the end.

setInterval(function(){

if(ytplayer.getPlayerState()==0)

{

if(self.repeat()=="repeaton.png")

{

ytplayer.playVideo();

}

else

{

self.playNextVideo();

}

}

setCookie("data",ko.toJSON(self.videos()));

},3000);

Moving a video up in the Videos array

I have added a link with each video which when clicked will move up the video in the playlist.

<tbody data-bind="foreach: videos">

<tr>

<td ><img alt="" data-bind="attr: { src: isrc}"/>

<a data-bind="text: name" id="videolink" style="margin-top: 2px;"></a>

<p style="height: 30px;overflow: hidden" data-bind="text: desc" ></p>

<a href="#" data-bind="click: $root.playVideo" style="float: none;">Play</a> |

<a href="#" data-bind="click: $root.removeVideo" style="float: none;">Delete</a> |

<a href="#" data-bind="click: $root.moveUp" style="float: none;">Move Up</a> |

</td>

</tr>

</tbody>

Here the click attribute of the a tag is binded to moveUp function below

self.moveUp=function(Video){

var length=self.videos().length;

var videoIndex=0;

for(var i=0;i<length; i++)

{

if(self.videos()[i]==Video)

{

videoIndex=i;

}

}

if(videoIndex>0)

{

var previousName=self.videos()[videoIndex-1].name();

var previousUrl=self.videos()[videoIndex-1].urlof();

var previousIsrc=self.videos()[videoIndex-1].isrc();

var previousDesc=self.videos()[videoIndex-1].desc();

var previousPlaying=self.videos()[videoIndex-1].playing();

self.videos()[videoIndex-1].name(self.videos()[videoIndex].name());

self.videos()[videoIndex-1].urlof(self.videos()[videoIndex].urlof());

self.videos()[videoIndex-1].isrc(self.videos()[videoIndex].isrc());

self.videos()[videoIndex-1].desc(self.videos()[videoIndex].desc());

self.videos()[videoIndex-1].playing(self.videos()[videoIndex].playing());

self.videos()[videoIndex].name(previousName);

self.videos()[videoIndex].urlof(previousUrl);

self.videos()[videoIndex].isrc(previousIsrc);

self.videos()[videoIndex].desc(previousDesc);

self.videos()[videoIndex].playing(previousPlaying);

}

}

The function loops through the videos array and finds the index of the received video from the binding.

Then it checks if the video is not already at the beginning of the array. Then it swaps all the fields of the previous video element with this video element so that it moves up in the playlist.


Moving a video down in the Videos array

I have added a link with each video which when clicked will move down the video in the playlist.

<tbody data-bind="foreach: videos">

<tr>

<td ><img alt="" data-bind="attr: { src: isrc}"/>

<a data-bind="text: name" id="videolink" style="margin-top: 2px;"></a>

<p style="height: 30px;overflow: hidden" data-bind="text: desc" ></p>

<a href="#" data-bind="click: $root.playVideo" style="float: none;">Play</a> |

<a href="#" data-bind="click: $root.removeVideo" style="float: none;">Delete</a> |

<a href="#" data-bind="click: $root.moveUp" style="float: none;">Move Up</a> |

<a href="#" data-bind="click: $root.moveDown" style="float: none;">Move Down</a>

</td>

</tr>

</tbody>

Here the click attribute of the a tag is binded to the moveDown function below

self.moveDown=function(Video){

var length=self.videos().length;

var videoIndex=0;

for(var i=0;i<length; i++)

{

if(self.videos()[i]==Video)

{

videoIndex=i;

}

}

if(videoIndex<length-1)

{

var nextName=self.videos()[videoIndex+1].name();

var nextUrl=self.videos()[videoIndex+1].urlof();

var nextIsrc=self.videos()[videoIndex+1].isrc();

var nextDesc=self.videos()[videoIndex+1].desc();

var nextPlaying=self.videos()[videoIndex+1].playing();

self.videos()[videoIndex+1].name(self.videos()[videoIndex].name());

self.videos()[videoIndex+1].urlof(self.videos()[videoIndex].urlof());

self.videos()[videoIndex+1].isrc(self.videos()[videoIndex].isrc());

self.videos()[videoIndex+1].desc(self.videos()[videoIndex].desc());

self.videos()[videoIndex+1].playing(self.videos()[videoIndex].playing());

self.videos()[videoIndex].name(nextName);

self.videos()[videoIndex].urlof(nextUrl);

self.videos()[videoIndex].isrc(nextIsrc);

self.videos()[videoIndex].desc(nextDesc);

self.videos()[videoIndex].playing(nextPlaying);

}

}

The function loops through the videos array and finds the index of the received video from the binding.

Then it checks if the video is not already at end of the array. Then it swaps all the fields of the next video element with this video element so that it moves down in the playlist.


Document Ready Function

The function is called automatically at the end of loading of the page.

It check if the cookies has data of previously edited playlist. If it has then it loaded the data to the videos array so that the user can start where he left during his last visit.

$(document).ready(function() {

var data = JSON.parse(getCookie("data"));

if (data!=null && data!="")

{

self.videos.removeAll();

var length=data.length;

for (var i = 0; i <= length; i++) {

self.videos.push(new Video(data[i].name,data[i].desc,data[i].urlof));

};

}

});

}

Binding Model to the UI

ko.applyBindings(new ViewModel());


Setting and getting the Cookie

function setCookie(c_name,value)

{

var exdays=1000;

var exdate=new Date();

exdate.setDate(exdate.getDate() + 1000);

var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());

document.cookie=c_name + "=" + c_value;

}

function getCookie(c_name)

{

var c_value = document.cookie;

var c_start = c_value.indexOf(" " + c_name + "=");

if (c_start == -1)

{

c_start = c_value.indexOf(c_name + "=");

}

if (c_start == -1)

{

c_value = null;

}

else

{

c_start = c_value.indexOf("=", c_start) + 1;

var c_end = c_value.indexOf(";", c_start);

if (c_end == -1)

{

c_end = c_value.length;

}

c_value = unescape(c_value.substring(c_start,c_end));

}

return c_value;

}

Is Knockout JS a good library to create dynamic UI

See results

Is Youtube-Playlist.com a great Youtube Interface example of Knockout JS

See results

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      anonymous 

      2 years ago

      If you save a playlist into a link on one computer and use it on another computer with that link, will the playlist still be saved?

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)