var ItemView = Backbone.View.extend({
tagName:"li",
className:"l-item",
template:_.template("#tpl-list-item"),
.....
});
var ListView = Backbone.View.extend({
render:(){
this.collection.each(function(model){
this.$el.append(new ItemView({model:model}).render().$el);
});
}
});
<script id="tpl-list-item" type="text/template">
<div>
// other markup
<div>
</script>
As shown once I want to update the representation of the itemview, I will have to check both the js and the template file.
And I prefer to build the view from the template only to avoid set the representation in the code like :
<script id="tpl-list-item" type="text/template">
<li class="....">
<div>
// other markup
<div>
</li>
</script>
Is this possible?
You could use
setElement
to replace the view'sel
:In practice, it would look something like this:
and
ListView
wouldn't need to change.Demo: https://jsfiddle.net/ambiguous/fs9h6o09/
This approach will end up creating and throwing away a bunch of
<div>
nodes as the view will create empty<div>
s as theel
if you don't tell it to do something else viaid
,className
, ... properties. These extra<div>
s probably won't make any noticeable difference but you could use someel: '#no-such-id'
trickery to avoid them.Backbone doesn't set that much policy but it really does want to separate the
el
from what goes inside it. You don't have to follow this but you're going against the grain by doing it your way.