0

I want to add a custom HTML attribute to a view so that it shows when I render a View. This is my code:

var Song = Backbone.Model.extend({
    defaults: {
        title: 'Red',
        artist: 'Taylor Swift',
        filename: 'audio1.mp3',
        playlist: 0
    }
});

var Player = Backbone.View.extend({
    tagName: "audio",
    id: "player",
    //Can I add a custom HTML attr here? eg. onended="view.next()"
    newTemplate: _.template('<source src="<%= filename %>" >'),
    initialize: function(){
        this.render();
    },
    render: function(){
        var track = this.model.currentTrack
        var currentModel = _.find(this.model.models, function(arr){return arr.attributes.playlist == track});
        this.$el.html(this.newTemplate(currentModel.toJSON()));
        $(document.body).html(this.el);
    },
    next: function(){
        this.model.currentTrack++;
        console.log('currentTrack: ', this.model.currentTrack);
        this.render();
    }
});

var Playlist = Backbone.Collection.extend({
model: Song,
initialize: function(models,options) {
    _.extend(this,_.pick(options, 'currentTrack'));
}
});


var playlist = new Playlist([
    {
        title: 'Red',
        artist: 'Taylor Swift',
        filename: 'audio1.mp3',
        playlist: 1
    },
    {
        title: 'Style',
        artist: 'Taylor Swift',
        filename: 'audio2.mp3',
        playlist: 2
    }
],
    {
        currentTrack: 1
    });

So, basically I want to add an HTML listener to the rendered View (<audio onended="view.next()">)so when the audio is finished playing I can trigger the next method of the view. How can I do this?

I would prefer to use Backbone events to do this but according to this answer I have to trigger events from the HTML element.

medicengonzo
  • 479
  • 1
  • 7
  • 23

1 Answers1

2

So it turns out I was going totally wrong about this and the answer was quite simple.

I just have to treat it like any other event...

var Player = Backbone.View.extend({
    tagName: "audio",
    id: "player",
    //I add an events attribute with the event and the method to trigger.
    events: {
        'ended': 'next'
    },
    newTemplate: _.template('<source src="<%= filename %>" >'),
    initialize: function(){
        this.render();
    },

Thanks to mu is too short for the heads up. He also mentioned to check out delegate events

medicengonzo
  • 479
  • 1
  • 7
  • 23