[英]Backbonejs - View custom HTML attributes?
I want to add a custom HTML attribute to a view so that it shows when I render a View. 我想向视图添加自定义HTML属性,以便在渲染视图时显示它。 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. 因此,基本上,我想在呈现的View( <audio onended="view.next()">
)中添加HTML侦听器,以便在音频播放完毕后可以触发视图的next
方法。 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. 我更愿意使用Backbone事件来执行此操作,但是根据此答案,我必须从HTML元素触发事件。
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
他还提到要检查delegate events
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.