Backbonejs - 查看自定义HTML属性?

时间:2017-06-17 19:16:17

标签: javascript html5 events audio backbone.js

我想为视图添加自定义HTML属性,以便在呈现视图时显示。这是我的代码:

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
    });

所以,基本上我想为渲染的视图(<audio onended="view.next()">)添加一个HTML侦听器,所以当音频播放完毕后,我可以触发视图的next方法。我怎么能这样做?

我更愿意使用Backbone事件来执行此操作,但根据this answer我必须从HTML元素触发事件。

1 个答案:

答案 0 :(得分:2)

事实证明我对此完全错了,答案很简单。

我必须像对待任何其他事件一样对待它......

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();
    },

感谢mu is too short提醒。他还提到了delegate events