BB: Collection View
http://codebeerstartups.com/2012/12/9-collection-views-in-backbone-js-learning-backbone-js/
by kyllle
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.2/backbone-min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css">
<div class="js-ctn"></div>
<script type="text/html" class="js-template">
<h1>Hey, <%= name %></h1>
<p><%= playerPoints %></p>
<ul>
<% _.each(teams, function(team) { %>
<li><%= team.name %> (<%= team.location %>) - <small><%= team.manager %></small></li>
<% }) %>
</ul>
</script>
CSS
@import url(http://fonts.googleapis.com/css?family=Roboto:300,400,500);
body {
font-family: Roboto;
color: #191919;
}
a {
color: #191919;
}
JavaScript
console.clear();
// Dummy Data
var data = [
{
"id": 1,
"name": "John Doe",
"teams": [
{
"id": 12,
"name": "Manchester United",
"manager": "Louis van Gaal",
"location": "Manchester"
}, {
"id": 18,
"name": "Everton",
"manager": "Roberto Martinez",
"location": "Liverpool"
}
],
"playerPoints": 14789,
"teamsAvailable": 2,
"teamsDeleted": 8
}, {
"id": 2,
"name": "Joe Bloggs",
"teams": [
{
"id": 4,
"name": "Arsenal",
"manager": "Arsene Wenger",
"location": "London"
}
],
"playerPoints": 4899,
"teamsAvailable": 3,
"teamsDeleted": 2
}
]
// Classes
var PersonModel = Backbone.Model.extend();
var PersonCollection = Backbone.Collection.extend({
model: PersonModel
});
var PersonCollectionView = Backbone.View.extend({
tagName: 'ul',
render: function() {
this.collection.each(this.addPerson, this);
return this;
},
addPerson: function(person) {
var personView = new PersonView({
model: person
});
this.$el.prepend( personView.render().el )
}
});
var PersonView = Backbone.View.extend({
tagName: 'li',
template: _.template( $('.js-template').html() ),
render: function() {
this.$el.html( this.template( this.model.toJSON() ) ); //or this.model.attributes if toJSON() overrid
return this;
}
});
// Setup
var personCollection = new PersonCollection(data, {parse:true});
var personCollectionView = new PersonCollectionView({
collection: personCollection
});
// Add to DOM
$('.js-ctn').html(personCollectionView.render().el);