Search code examples
backbone.jshtml5-audiobackbone-events

backbone.js bind to audio events


How to do it? I searched Stack Overflow, find one similar result, but it doesn't work.

Here's my code:

var Player = Backbone.Model.extend({
    defaults: {
        //some variables
    },
    //creating audio element
    setAudio: function(ogglink, mp3link){
        //code, that works
    }
});     
var Playlist = Backbone.Collection.extend({ 
    model: Player
});
var MyPlaylist = new Playlist([ 
    //some songs here
]);    
var OneSongView = Backbone.View.extend({     
    //added some 'template' and 'el' code
    initialize: function () {
        this.model.bind("change", this.render, this);   
    },
    render: function (eventName) {
        $(this.el).html(this.template(this.model.toJSON()));
        this.model.setAudio(this.model.get("ogglink"), this.model.get("mp3link"));
        return this;
    },
    events: {
        //declaration of some events
    },
    //event functions
});    
var AppRouter = Backbone.Router.extend({
    //router code
});    
var app = new AppRouter();
Backbone.history.start();

If I add in events something like timeupdate: somefunc, it'll not work, if I add code like here, I'll have errors :(


Solution

  • All Backbone.View event handlers are delegated to the view's el. This means that any events that fire inside the view must bubble/propagate up to its el before your handlers will catch them.

    Unfortunately for you, HTML5 audio and video elements do not propagate their events up through the DOM the way most other elements do. The only way to handle these events is to add eventListeners directly to the <audio> element after it has been inserted into the DOM.