Search code examples
javascriptbackbone.jsjplayer

BackboneJS How to add JPlayer


I'm trying to add the Jquery Jplayer http://jplayer.org to my Backbone App but cant get it running. I set up the script into my RequireJS config file and my console tells me that the script is loaded. So I setup a View to test it which looks like this:

define([

'app',
'backbone',
'audioplayer'

],

function (App, Backbone, audioplayer) {

    var audioplayer = App.module();

    var audioplayer = Backbone.View.extend({
        template: 'audioplayer',
        initialize: function() {
            var self = this;
            $("#jquery_jplayer_1").jPlayer({
                ready: function(event) {
                    $(this).jPlayer("setMedia", {
                        title: "Cro Magnon Man",
                        mp3: "http://jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3",
                        oga: "http://jplayer.org/audio/ogg/TSP-01-Cro_magnon_man.ogg"
                    });
                },
                swfPath: "http://jplayer.org/latest/js",
                supplied: "mp3, oga"
            });          
        }
    });

    return audioplayer;
}
);

and my HTML template:

<div id="jquery_jplayer_1" class="jp-jplayer"></div>

<div id="jp_container_1" class="jp-audio">
   <div class="jp-type-single">
    <div class="jp-gui jp-interface">
        <ul class="jp-controls">

            <li><a href="javascript:;" class="jp-play" tabindex="1">play</a></li>
            <li><a href="javascript:;" class="jp-pause" tabindex="1">pause</a></li>
            <li><a href="javascript:;" class="jp-stop" tabindex="1">stop</a></li>
            <li><a href="javascript:;" class="jp-mute" tabindex="1" title="mute">mute</a></li>
            <li><a href="javascript:;" class="jp-unmute" tabindex="1" title="unmute">unmute</a></li>
            <li><a href="javascript:;" class="jp-volume-max" tabindex="1" title="max volume">max volume</a></li>
        </ul>

        <div class="jp-progress">
            <div class="jp-seek-bar">
                <div class="jp-play-bar"></div>
            </div>
        </div>
        <div class="jp-volume-bar">
            <div class="jp-volume-bar-value"></div>
        </div>
        <div class="jp-current-time"></div>
        <div class="jp-duration"></div>                   
    </div>
    <div class="jp-details">
        <ul>
            <li><span class="jp-title"></span></li>
        </ul>
    </div>
  </div>
</div>

All I got is the html on my view, but I'm not able to play the track

what am I doing wrong?


Solution

  • So the issue is you are trying to init player with non-existing DOM. Here is a rule that any Jquery plugins should be launched after BB or Marionette View render.

    So in your case u have to move $("#jquery_jplayer_1").jPlayer({}) after view render like

    render: function() {
        .... some render logic ....
        $("#jquery_jplayer_1").jPlayer({...})
    }