I would like to understand about Backbone templating approaches. I’m using Marionette to deal with CollectionViews.
What is the difference to do this:
// This approach is working fine.
<script type="text/template" id="single-item">
<li><strong><%= userName %></strong></li>
</script>
Instead of this:
<ul>
each( Loop into each collection item ) :
<li><%= item.property %></li>
endEach;
</ul>
The Marionette CollectionView make a view instance per collection item. So you have the complete control over the item.
Say you want to list users with a single view that handles all the list itself. It would look something like this:
And the template
It's super simple and looks good from there.
But then, you want to add an edit button for each user in the list. There begins the real problem with the approach above. You'd have to guess which element was clicked on, or put the user id in a
data-idattribute in the template. All of that sucks.The
CollectionViewlet you deal with that easily and everything is scoped to its sole responsibility.Make an item view:
With a super simple template.
Then use it within your list view.
After that, adding features to your item view is really easy. It's even reusable in different list since the list and the item are decoupled.