1

I want to use jwplayer on a Single Page App built using Durandal framework. The idea is to create a persistent audio player, unaffected by the application's navigation. But I haven't been able to load jwplayer in Durandal.

I've successfully loaded jwplayer on a simple html file using Require.js. But this method doesn't seem to work on Durandal (which also uses Require.js).

This is my code on 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 () {
        ...
    }
  }; 
});

And inside the shell.html I have this code: <div id="player">loading player...</div>

This is the error message I get:

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

It seems that the player element is unrecognizable inside a Durandal module. What caused this problem? How do I add a jwplayer inside a Durandal module?

Community
  • 1
  • 1

1 Answers1

4

As you already figured out, it looks like the player element isn't recognized when the code is executing. When the module is loading for the first time, the DOM definitely isn't ready. It may not even be ready during the activate() callback function. The right time to setup the jwplayer is probably in the viewAttached() callback.

You can read more about the viewAttached callback here in the Composition Callbacks section: http://durandaljs.com/documentation/Hooking-Lifecycle-Callbacks/

Something like this:

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"
        }]
      });
    }
  }; 
});
Joseph Gabriel
  • 8,339
  • 3
  • 39
  • 53
  • Thank you very much, this works perfectly. I was also wondering whether the DOM caused that problem, but I haven't really know much about Durandal's callbacks to fix that problem. – Arie M. Prasetyo Apr 05 '13 at 03:34