将YouTube视频绑定到来自单独JS文件的Div元素

时间:2014-02-25 19:44:30

标签: javascript knockout.js youtube phonejs devextreme

我有一个问题是将YouTube视频嵌入到PhoneJS单页移动应用程序中。在PhoneJS中,JS脚本在不同的文件中定义。所以我像这样定义了HTML div:

<div id="player"></div>

现在在JS文件中,我这样做了:

function getVideo() {        
    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var playerDiv = document.getElementById('player');
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var player;
    function onYouTubeIframeAPIReady() {
        player = new YT.Player(playerDiv, {
            height: '250',
            width: '444',
            videoId: sIFYPQjYhv8               
        });
    }        
}

当我运行并查看调试器时,会调用Youtube并收到响应,但它不会显示在视图上。

好的,因为我使用KnockoutJS绑定,我修改了html视图中的div,如下所示:

<iframe id="player" type="text/html" width="444" height="250" frameborder="0" data-bind="attr: { src: src }"></iframe>

然后传入src视频ID:

src: ko.observable('http://www.youtube.com/embed/' + sIFYPQjYhv8 + '?autoplay=1')

但是在这种情况下,在调试器中,甚至没有对Youtube进行调用。什么都没发生。实际上我更喜欢使用API​​调用而不是第二种方法。

关于如何使第一种方法有效的任何建议?我的意思是使用API​​调用?

EDIT 只是想提一下,当我在视图中添加下面的代码时,视频流是正常的。

<h1>Video</h1>
        <div id="player"></div>
        <script>
            var tag = document.createElement('script');
            tag.src = "https://www.youtube.com/iframe_api";
            var playerDiv = document.getElementById('player');
            var firstScriptTag = document.getElementsByTagName('script')[0];
            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

            var player;
            function onYouTubeIframeAPIReady() {
                player = new YT.Player(playerDiv, {
                    height: '250',
                    width: '444',
                    videoId: 'sIFYPQjYhv8'
                });
            }
        </script>

1 个答案:

答案 0 :(得分:1)

我认为最简单的方法是使用自定义绑定处理程序,并在onYouTubeIFrameAPIReady回调中设置标志

Sample jsFiddle

ko.bindingHandlers['player'] = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // Check if global script and function is declared.
        if ( !document.getElementById('playerScript') ) {
            // Create script
            var tag = document.createElement('script');
            tag.src = "https://www.youtube.com/iframe_api";
            var playerDiv = document.getElementById('player');
            var firstScriptTag = document.getElementsByTagName('script')[0];
            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

            // Create global function that their API calls back
            window.playerReady = ko.observable(false);
            window.onYouTubeIframeAPIReady = function() {
                window.playerReady(true);
            };
        }
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {

        var value = valueAccessor(),
            id = value.id(),
            height = ko.unwrap(value.height) || '250',
            width = ko.unwrap(value.width) || '444'
        ;

        if ( !value.id()) {
            return;
        }

        if ( !window.playerReady() ) {
            // YT hasn't invoked global callback.  Subscribe to update
            var subscription;
            subscription = window.playerReady.subscribe( function(newValue) {
                 if ( newValue ) {
                     subscription.dispose();
                     // Just get this binding to fire again
                     value.id.notifySubscribers(value.id());
                 }
            });
        } else {

            var player = new YT.Player( element, {
                height: height,
                width: width,
                videoId: id 
            });
        }
    },
}

现在将玩家div更改为

<div data-bind="player: { id: id, height: height, width: width }"></div>

最后绑定

var vm = { 
    id: 'sIFYPQjYhv8',
    height: '250',
    width: '444'
};
ko.applyBindings( vm )

修改

要删除对窗口的依赖,请将脚本标记添加回新的脚本元素,如下所示,修改其回调并使用setTimeout而不是“playerReady”observable

HTML脚本

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
tag.setAttribute('id', 'playerScript');
tag.setAttribute('data-ready', 'false');
...

function onYouTubeIframeAPIReady = function() {
    document.getElementById('playerScript').setAttribute('data-ready', 'true');
};

玩家绑定

    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {

        var value = valueAccessor(),
            id = value.id(),
            height = ko.unwrap(value.height) || '250',
            width = ko.unwrap(value.width) || '444',
            playerScript = document.getElementById('playerScript')
        ;

        if ( !value.id()) {
            return;
        }

        if ( !playerScript || playerScript.getAttribute('data-ready') !== 'true' ) ) {
            // YT hasn't invoked global callback.  
            setTimeout( function() {
                 value.id.notifySubscribers(value.id());
            }, 50);
        } else {

            var player = new YT.Player( element, {
                height: height,
                width: width,
                videoId: id 
            });
        }
    }