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 could always use setElement
:
setElement
view.setElement(element)
If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached
$el
reference and move the view's delegated events from the old element to the new one.
and forget about tagName
completely:
PhotoListItemView = Backbone.View.extend({
template: _.template($('#tpl-PhotoListItemView').html()),
render: function() {
this.setElement(this.template(this.model.toJSON()));
return this;
}
});
Demo: http://jsfiddle.net/ambiguous/XWEMg/
As an aside, <span>
is a poor choice for a container (even a temporary one) due to its limited permitted content; you risk the browser rearranging your HTML to get something valid if you start throwing arbitrary HTML into a <span>
. A <div>
is a much safer choice as it can hold pretty much anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With