调用youtube构造函数方法时丢失此上下文

时间:2014-06-22 14:37:08

标签: javascript youtube

我使用youtube iframe api创建了一个youtube播放器,我正在收听ENDED事件,但我意识到我失去了对this的引用,后者成了窗口,但我是真的不确定如何解决这个问题。我已经尝试将this绑定到contsructor等,但没有任何喜悦,所以你可以帮助你们。

JS

startPlayer: function (videoId) {

            var instance = this;
            console.log('startPlayer', instance);

            if( instance.flags.isPlaying ) {

                instance.selectors.playerCtn.empty();

                instance.flags.isPlaying = false;

            }

            instance.selectors.playerCtn.append('<div id="player"></div>');

            instance.player = new YT.Player('player', {
                height: '390',
                width: '640',
                videoId: videoId,
                events: {
                    'onReady': this.onPlayerReady,
                    'onStateChange': this.onPlayerStateChange
                }
            });

            instance.flags.isPlaying = true;
        },

onPlayerStateChange: function (event) {
            console.log('onPlayerStateChange');

            var instance = this;

            console.log(instance); //undefined??

            if (event.data == YT.PlayerState.PLAYING) {
                console.log('PLAYING...');
            }

            if (event.data == YT.PlayerState.PAUSED) {
                console.log('PAUSED...');
            }

            if (event.data == YT.PlayerState.ENDED) {

                console.log('what is this', instance);

                // if instance.counter === instance.playlist
                if (instance.counter === instance.playlist) {
                    console.log('you\'ve come to the end of your playlist');
                    // Display message or go back to first?
                    return;
                }

                // Increase the counter
                instance.counter++
                // Set the new current element
                instance.current = instance.selectors.listItems[instance.counter];

                console.log(instance.counter);
                console.log(instance.current);

                // Get the new current element data-id
                var videoId = instance.current.attr('data-id');

                // Start the player
                startPlayer(videoId);
            }

            if (event.data == YT.PlayerState.BUFFERING) {
                console.log('BUFFERING...');
            }
        }

测试页 http://go.shr.lc/1lh2dmu

1 个答案:

答案 0 :(得分:1)

events: {
    'onReady': this.onPlayerReady.bind(this),
    'onStateChange': this.onPlayerStateChange.bind(this)
}

此外,为什么var instance = this;?键入的时间this要短得多,而且在任何闭包中都没有使用instance