Composite View: Grid View
A grid view build w/ Marionette
by derickbailey
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script src="http://marionettejs.com/downloads/backbone.marionette.js"></script>
<script id="grid-template" type="text/template">
<thead>
<tr>
<th>Username</th>
<th>Full Name</th>
</tr>
</thead>
<tbody></tbody>
</script>
<script id="row-template" type="text/template">
<td>
<%= username %>
</td>
<td>
<%= fullname %>
</td>
</script>
<div id="grid">
</div>
CSS
table, tr, td, th, thead {
padding: 5px;
margin: 5px;
border: 2px solid #ccc;
}
thead {
background-color: #555;
color: #fff;
}
JavaScript
// A Grid Row
var GridRow = Backbone.Marionette.ItemView.extend({
template: "#row-template",
tagName: "tr"
});
// The grid view
var GridView = Backbone.Marionette.CompositeView.extend({
tagName: "table",
template: "#grid-template",
itemView: GridRow,
appendHtml: function(collectionView, itemView){
collectionView.$("tbody").append(itemView.el);
}
});
// ----------------------------------------------------------------
// Below this line is normal stuff... models, templates, data, etc.
// ----------------------------------------------------------------
var userData = [
{
username: "dbailey",
fullname: "Derick Bailey"
},
{
username: "jbob",
fullname: "Joe Bob"
},
{
username: "fbar",
fullname: "Foo Bar"
}
];
var User = Backbone.Model.extend({});
var UserCollection = Backbone.Collection.extend({
model: User
});
var userList = new UserCollection(userData);
var gridView = new GridView({
collection: userList
});
gridView.render();
console.log(gridView.el);
$("#grid").html(gridView.el);