首页 > 解决方案 > youtube api 的异步调用导致 player.getDuration is not a function 错误

问题描述

将 Youtube IFrame api 与 Knockout JS 一起使用时出现类型错误。视频正在 ftl 上加载,但 player.getDuration() 在播放器对象完全初始化之前由于异步调用而导致错误。有谁知道如何在 Knockout JS 中解决这个问题?

我尝试了回调方法,然后 & done 方法,但在 Knockout JS 中没有运气。

错误详情:

Uncaught TypeError: player.getDuration is not a function
    at Object.getTotalDuration (youtube-player-module.require.js:28)
    at list-view-module.require.js:102
    at Object.onYouTubeIframeAPIReady (youtube-player-module.require.js:24)
    at ViewModel.self.submitform(list-view-module.require.js:101)
    at Modal.eval (eval at parseBindingsString (knockout-latest.js:68), <anonymous>:3:96)
    at HTMLInputElement.<anonymous> (knockout-latest.js:89)
    at HTMLInputElement.dispatch (jquery.js:5183)
    at HTMLInputElement.elemData.handle (jquery.js:4991)

列表视图模块.require.js

youtubeplayermodule.onYouTubeIframeAPIReady(vid,function () 
{ 
var duration= youtubeplayermodule.getTotalDuration(); 
});

youtube-player-module.require.js

let player = ko.observable();

function onYouTubeIframeAPIReady(vid, doneCallBack) {
    player =  new YT.Player('video-placeholder', {
        videoId: vid,
        events: {
            'onReady': initialize
        }
    });
    doneCallBack();
}

function getTotalDuration() {
    return player.getDuration();
}

function initialize(){
    alert('initiaze');
}

标签: javascriptyoutube-apiyoutube-data-api

解决方案


推荐阅读