I just started with backbone.js, and one thing that I noticed is that sometimes I do not want any tagName to contain/encapsulate my view’s template code. If I leave it at '' or 'span', I get unneccessary div and span in my code.
The alternative that I found is to remove the containing tag from my template (<div class="photo_box"> in my example as shown below), and use that as the tagName in my view. Most of the time, this tag will contain a class (.photo_box), and I still have to perform an addClass to (this.el). I dont really like scattering up my template code.
Is there another way?
JS
// Views
PhotoListView = Backbone.View.extend({
tagName: 'span',
render: function() {
_.each(this.model.models, function(photo) {
$(this.el).append(new PhotoListItemView({ model: photo }).render().el);
}, this);
return this;
}
});
PhotoListItemView = Backbone.View.extend({
tagName: 'span',
template: _.template($('#tpl-PhotoListItemView').html()),
render: function() {
$(this.el).html(this.template( this.model.toJSON() ));
return this;
}
});
HTML
<!-- Templates -->
<script type="text/template" id="tpl-PhotoListItemView">
<div class="photo_box">
<div class="photo_container">
<img src="img/profiling/<%= photo_id %>.jpg" class='photo' />
</div>
</div>
</script>
Result
<div id="photo_list">
<span>
<span>
<div class="photo_box">
<div class="photo_container">
<img src="img/profiling/f_001.jpg" class="photo">
</div>
</div>
</span>
<span>
<div class="photo_box">
<div class="photo_container">
<img src="img/profiling/f_002.jpg" class="photo">
</div>
</div>
</span>
</span>
</div>
You don’t need to manually add the class-name. You can use the
classNameproperty:Btw, I recommend this HTML structure: