Search code examples
javascriptdata-bindingyoutubeevent-handlingdom-events

How can I pass data to the onStateChange event handler with Youtube iframe API


I am building a small video player with Javascript for a website. I have a list with videos in JSON. I instantiate my player with

var Videoplayer = new myVideoPlayer(data);

Because the list contains videos from Vimeo and YouTube, I want to handle both APIS inside this object. Inside I have functions like:

setVideo(videoId)

to select and play a video, or

markVideoAsSelected(video)

to add classes in html.

So far everything went pretty smooth, but I am hitting a wall now. When I load the YouTube player via the API, I add the:

events : {
    'onStateChange': self.YTonStateChange
}

Everything I want is bound to the Videoplayer instance I created in the beginning. On state change, I run this:

YTonStateChange : function(e){
    var self = this
    switch(e.data){
        //Video ended code 0
        case 0:
            setTimeout(self.switchToNextVideo, 3000);
        break;
    }
}

The problem:

this is now bound to the event from the YouTube API and I lost my object. I don't know, how I can pass my object instance along with the event to the event handler?! There are things in there that I need for further steps, how can I get it back?


Solution

  • Just bind the context to 'self' like that :

    events : {
        'onStateChange': self.YTonStateChange.bind(self)
    }
    

    It will force 'this' value to 'self' in the YTonStateChange callback. Hope it helps ;)