Pregunta

Attempting to implement a playlist function along with a listening history. Thumbnails of videos for the playlist are dynamically dragged/dropped/sorted by the user into a div. Each time a thumbnail is clicked, the video is loaded in the player and the video is added to the history (subHist.click()).

Because the videos are dynamically created, I cannot create the event listener to move on to the next video at the beginning, and have to add it later. The problem with that is I have the listening history function within the function that creates the event listener, so the event listener is called increasing number of times as we go through the playlist, meaning a video appears multiple times in the playlist when clicked only once.

This might make more sense with some code:

$('#Playlist').on('click', '.playlistYT', function(){
    $('#subHistory').click();
    videoID = $(this).attr("src").slice(27,38);
    $('#infoID').val(videoID);
    player.loadVideoById(videoID ); 
    var nextVideo = $(this).parent().next().find('.playlistYT');
    player.addEventListener('onStateChange', function stopCycle(event) {
    if (event.data == YT.PlayerState.ENDED) {
    $(nextVideo).click();
  }
});      
});

The images are of the class .playlistYT once they are dropped (i.e. this class does not exist before any videos are dropped), and $('#subHistory').click() which adds the video the listening history.

If I move the var nextVideo within the addEventListener, then it does not recognise it (can't use $(this) as it seems to redefine that to the event within the event handler). Moving $('#subHistory').click() to the stopCycle function seems to make no difference.

Spent past couple of days playing around with .one, .off, .live, can't seem to crack it. removeEventListener doesn't seem to make any difference, either. I thought of adding a hidden video to the playlist but that then becomes a question of making sure that video doesn't appear in users' listening history/playlists.

¿Fue útil?

Solución

The onStateChange event that is passed to the event listener has the 'data' object, but it also has the 'target' object that represents the player that raised the event. So for example, you could define the function that handles onStateChange when you initialize the iFrame API, and within that listener function, you could use something like:

event.target.getVideoData().video_id

To find the ID of the playing video that raised the event. Based on your sample code, it looks like knowing the video ID may help you write the proper jQuery selector to find where in your DOM the video is, and then navigate to the next one from there. Hence your event listener will only be defined once but it will be able to handle the dynamic nature of your app's playlist.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top