在Durandal中加载jwplayer

时间:2013-04-04 18:23:39

标签: requirejs jwplayer durandal

我想在使用Durandal框架构建的单页面应用程序上使用jwplayer。我们的想法是创建一个不受应用程序导航影响的持久性音频播放器。但是我无法在Durandal中加载jwplayer。

我已成功loaded jwplayer on a simple html file using Require.js。但是这种方法似乎不适用于Durandal(也使用Require.js)。

这是我在 shell.js 上的代码:

define(['jwplayer/jwplayer','durandal/plugins/router','durandal/app'], function (jwplayer,router,app) {

  jwplayer.api('player').setup({
    width: '320',
    height: '40',
    sources: [{
        file: "rtmp://127.0.0.1:1935/vod/mp3:sample_1.mp3"
    },{
        file: "http://127.0.0.1:1935/vod/sample_1.mp3/playlist.m3u8"
    }]
  });

  return {
    router: router,
    activate: function () {
        ...
    }
  }; 
});

shell.html 中,我有以下代码:<div id="player">loading player...</div>

这是我收到的错误消息:

Uncaught TypeError: Cannot read property 'id' of null jwplayer.js:37

在Durandal模块中似乎无法识别player元素。是什么导致了这个问题如何在Durandal模块中添加jwplayer?

1 个答案:

答案 0 :(得分:4)

正如您已经想到的那样,代码执行时看起来无法识别播放器元素。当模块第一次加载时,DOM肯定没有准备好。在activate()回调函数期间甚至可能没有准备好。设置jwplayer的正确时间可能在viewAttached()回调中。

您可以在撰写回调部分中详细了解viewAttached回调:http://durandaljs.com/documentation/Hooking-Lifecycle-Callbacks/

这样的事情:

define(['jwplayer/jwplayer','durandal/plugins/router','durandal/app'], function (jwplayer,router,app) {

  return {
    router: router,
    activate: function () {
        ...
    },
    viewAttached: function(){
      jwplayer.api('player').setup({
        width: '320',
        height: '40',
        sources: [{
            file: "rtmp://127.0.0.1:1935/vod/mp3:sample_1.mp3"
        },{
            file: "http://127.0.0.1:1935/vod/sample_1.mp3/playlist.m3u8"
        }]
      });
    }
  }; 
});